Bit Manipulation

If you have any doubts in the below, contact us by dropping a mail to the Kung Fu Panda. We will get back to you very soon.

Basics

Bit

Byte

1 byte = 8 bits

Basics of Boolean Algebra

Additional

Usages

Example Interview Questions

Multiply a no by 2

Divide a no by 2

set the kth bit of N(counting from right) to 1.

clear the kth bit of N(counting from right).

toggle/flip the kth bit of N(counting from right).

turn off the first set bit(1 bit) of a number N.

get the count of 1s in a no.

	// Idea: N & 1 gives the first bit.
	int count = 0;
	
	while(n > 0) {
		count = count + (N & 1);
		N = N >> 1;
	}
	
	return count;
	

Alternate method: suggested by thevagabond85 in comments.

	int count = 0;
	
	while(n) {
		n = n & (n-1); // turn off the first set bit(1 bit) of a number N.
		count++;
	}
	
	return count;
	

How to calculate the no of bits to convert from no A to no B.

Check if N is a power of 2 or not.

Check if N is a power of 4 or not.

How to get the last 3 bits of an integer.

Get the 5 highest bits of an integer(8 bit integer).

check whether the kth bit in N is 1.

swap two nos using bitwise operations.

swap even and odd bits in a no(4 byte integer)

Misc