Home > other >  get the value of a bit from an unsigned char
get the value of a bit from an unsigned char

Time:11-23

Considering : value : An unsigned integer on 32 bits.

pos : which is the index of the bit to get from value. ( The index 0 is the first bit so the lowest value )

I want to implement a function get_bit(value,pos) so that it retruns the value of the bit (0 or 1) from the unsigned integer value at index pos

for example value = 5 (0101 in binary) then get_bit(5,0)=1 get_bit(5,1)=0 get_bit(5,2)=1

Can you explain me what is the most optimized way to solve this problem ?

CodePudding user response:

You can achieve it with

(value >> pos) & 0x01;

(value >> pos)         // Shift the value pos positions to the right
               & 0x01; // Only take the first bit (lowest value)

I recommend researching "bit shift" (the >>) and "bit mask" (the &) for example here to get a better understanding about the subject.

  •  Tags:  
  • c
  • Related