Inverting Bits

Occasionally it is necessary to invert the bits for a number. Most often, this is part of custom algorithms or checksum calculations. It raises the general question: what’s the easiest way to do this?

“Bit-Flipping” can be done with the -bnot operator like this:

$number = 76
[Convert]::ToString($number,2)

$newnumber = -bnot $number
[Convert]::ToString($newnumber,2)

The result shows one caveat, though:

 
1001100
11111111111111111111111110110011 
 

The operator always acts on signed 64-bit numbers. A better approach may be to use the -bxor operator and provide your own bit mask that you want to flip. For a byte, the bit mask would be 0xFF, and for an Int32, it would be 0xFFFFFFFF. Here is an example to flip the bits for a byte. We padded the string representation to 8 characters to make leading zeroes visible:

$number = 76
[Convert]::ToString([byte]$number,2).PadLeft(8, '0')

$newnumber = $number -bxor 0xFF
[Convert]::ToString($newnumber,2).PadLeft(8, '0')

The result matches:

 
01001100
10110011 
 

Your learning points:

  • PowerShell comes with a rich set of binary operators that all start with -b…
  • To invert (flip) bits, you can use -bnot. To flip only some bits, use -bxor with your bit mask

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...