Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get the value of a bit from an unsigned char

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading