Extract Bits Out of Variable in C Programming using Bitwise Operators

If someone wants to extract Bits out of a variable, below-mentioned code explains how it can be done.
  1. First of all, we need an array of a 1-byte variable to store all the extracted bits.
  2. Then we need a mask variable which is used to check whether a bit is ON or OFF.
  3. Then we have to shift 1 bit to the left i times to make masked value.
  4. The final step is extracting bits using Bitwise AND and Right-Shift Operator.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
char bits[7]={0};
char extract_bits(char val)
{
   short mask;
   int i;
   for(i=0; i< 7; i++){
   mask= 1 << i;
   bits[i] = (val& mask)>>i;
   printf("%d\n",bits[i]);  
}

Featured post

Extract Bits Out of Variable in C Programming using Bitwise Operators

If someone wants to extract Bits out of a variable, below-mentioned code explains how it can be done. First of all, we need an array of a ...

Popular