Skip to main content

Bit Manipulation

Bit manipulation involves the direct manipulation of bits within a binary representation of data. It uses boolean algebra operations for the same.

bit vectors are very important

Bit vectors are nothing but an array of bits. In all programming problems, we just use an integer to represent a bit vector since integers or anything for that matter are just a sequence of bits.

Bit vectors are used in many solutions. It's very useful to understand how data manipulation and extraction in bit vectors work.

use of 1 as mask

In all the below steps, we use 1 as the mask. This means it's an integer 1 where just last bit is set to 1. We then use shift operators to move this 1 at different positions.

PurposeOperationExpressionWhat it DoesMental Model
Set a bitOR |x |= (1 << i)Forces bit i to 1โ€œTurn ON this switchโ€
Clear a bitAND + NOT & ~x &= ~(1 << i)Forces bit i to 0โ€œTurn OFF this switch"
Toggle a bitXOR ^x ^= (1 << i)Flips bit iโ€œFlip the switchโ€
Check a bitAND &(x & (1 << i)) != 0Tests if bit i is 1โ€œIs this switch ON?โ€
Extract a bitShift + AND(x >> i) & 1Gets value of bit iโ€œRead this switchโ€
Clear lowest set bitAND trickx &= (x - 1)Removes rightmost 1โ€œDrop the last ON bitโ€
Isolate lowest set bitAND trickx & -xKeeps only lowest 1โ€œFind first ON switchโ€
Create maskShift1 << iSingle bit maskโ€œPointer to one bitโ€
Invert all bitsNOT ~~xFlips every bitโ€œReverse all switchesโ€
why xโˆ’1x-1 is important?

xโˆ’1x-1 mentioned above is another concept to remember. When we minus 1 from any number, it will always toggle all ending zeros to ones and the first available 1 to 0. Then performing an AND between these two values will operate on the rightmost 1 bit.

what x&โˆ’xx\&-x means?

Important nuance to keep in mind is, between x and -x the bits are same until the first/lowest 1, after that all bits are opposite between x and -x.

whats the variable in bit shift operators

It always means the number of times the bit sequence must be moved left or right. Or other way to look at it's, to say move the bit at that index position to 0th0^{th} position.

smallest mental model to remember
  • OR - sets a specific bit to 1.
  • AND - sets a specific bit to 0 (but the mask must be 0 at that position and 1 at rest.)
  • XOR - Changes 1 to 0 and 0 to 1.
checking vs extracting
  • Checking returns boolean - true or false.
  • Extracting returns actual value - 0 or 1

It's important to know this distinction.