简体   繁体   中英

extracting a bit from a buffer

Whats the best way to extract a bit from an unsigned char .In my opinion ,I think this works perfectly well`

int bit;
  unsigned char buffer;
  bit= 1 & (buffer>>3) //`if i want to extract the fourth bit
  bit=  1 & (buffer>>7)//if i want to extract the 8 bit

If you do not care for the bit to be in the least significant position (eg because you need it for a boolean condition) you can do this:

if (buffer & (1<<3)) {
    // ...
}

This may be faster because of constant folding : it is only one operation at runtime instead of two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM