Grabbing n bits from a byte

后端 未结 6 2020
走了就别回头了
走了就别回头了 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:29

    int x = (number >> 3) & 0x1f;

    will give you an integer where the last 5 bits are the 8-4 bits of number and zeros in the other bits.

    Similarly,

    int y = number & 0x7;

    will give you an integer with the last 3 bits set the last 3 bits of number and the zeros in the rest.

提交回复
热议问题