Managing Bit Flags (Part 3)

by Mar 7, 2017

Setting or clearing bit flags in a decimal is not particular hard but unintuitive. Here is a quick refresher showing how you can set and clear individual bits in a number:

$decimal = 6254
[Convert]::ToString($decimal, 2)

# set bit 4
$bit = 4
$decimal = $decimal -bor [Math]::Pow(2, $bit)
[Convert]::ToString($decimal, 2)

# set bit 0
$bit = 0
$decimal = $decimal -bor [Math]::Pow(2, $bit)
[Convert]::ToString($decimal, 2)

# clear bit 1
$bit = 1
$decimal = $decimal -band -bnot [Math]::Pow(2, $bit)
[Convert]::ToString($decimal, 2)

The result illustrates what the code does. ToString() shows bits from right to left, so bit #0 is to the far right. In line 2 and 3 below, two individual bits were set without tampering with the others. In the last line, a bit was cleared.

 
1100001101110
1100001111110
1100001111111
1100001111101 
 

Twitter This Tip! ReTweet this Tip!