## 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

1 2 3 4 |
0000 0001 (1) 0000 0010 (2) - = 0000 0000 (0) |

Result is 0

### OR Operation

1 2 3 4 |
0000 0001 (1) 0000 0010 (2) = 0000 0011 (3) |

Result is 3.

### XOR or Exclusive OR Operation

1 2 3 4 |
0000 0001 (1) 0000 0010 (2) = 0000 0011 (3) |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include int main(int argc, char *argv[]) { int value = 100; int bit = 5; /* 1. To check if bit 5 is set. 2. Right shift with the bit number you want to check. 3. AND it with 1 afterwards. */ if ( (value >> bit) & 1) { /* Bit is set. */ printf("Bit %d is Set ", bit); } else { /* Bit is not set */ printf("Bit %d is not Set", bit); } } |

So What happens is;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
100 binary value is : 01100100 5 binary value is : 00000101 Right shift 100 with 5 would yield; 01100100 > 00000011 AND resulting value with 1 would yield; Right shifted value of 100 : 00000011 Binary value of 1 : 00000001 ======== 00000001 which concludes to true. That means bit number 5 is set in 100. |

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.