SHARE
How to find it a bit is set in a number

How to find If a bit is set in a number – or a specific bit in a number? Well the answer is pretty easy using BITWISE operators.

BITWISE operators are AND OR and XOR operators. These are special operators used for manipulation of binary digits i.e. 0-1.

Lets take a number “1” which corresponds to binary value “0000 0001”.

Now take another number “2” which corresponds to binary value = “0000 0010”.

You simply can’t add or multiple or divide them using Arthematic operators i.e. +  –  x  / . So in such case BITWISE operators are used.

AND Operation

Result is 0

OR Operation

Result is 3.

XOR or Exclusive OR Operation

Result for XOR is also 3.

You can read more about Binary Operators by Googling it.

C Code Example

So now how to find if a bit is set in a number or specific bit in a number. Lets take an example of integer number 100 and we want to find the 5th bit status.

So What happens is;

You can now compile this program and run it. Try changing bit number and see the result. For practice you can try with Left Shift BITWISE operator to see if you can find the right bit.

NO COMMENTS