Grabbing n bits from a byte

后端 未结 6 2018
走了就别回头了
走了就别回头了 2021-01-30 14:31

I\'m having a little trouble grabbing n bits from a byte.

I have an unsigned integer. Let\'s say our number in hex is 0x2A, which is 42 in decimal. In binary it looks li

6条回答
  •  醉酒成梦
    2021-01-30 15:25

    "grabbing" parts of an integer type in C works like this:

    1. You shift the bits you want to the lowest position.
    2. You use & to mask the bits you want - ones means "copy this bit", zeros mean "ignore"

    So, in you example. Let's say we have a number int x = 42;

    first 5 bits:

    (x >> 3) & ((1 << 5)-1);
    

    or

    (x >> 3) & 31;
    

    To fetch the lower three bits:

    (x >> 0) & ((1 << 3)-1)
    

    or:

    x & 7;
    

提交回复
热议问题