Grabbing n bits from a byte

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

    Say you want hi bits from the top, and lo bits from the bottom. (5 and 3 in your example)

    top = (n >> lo) & ((1 << hi) - 1)
    bottom = n & ((1 << lo) - 1)
    

    Explanation:

    For the top, first get rid of the lower bits (shift right), then mask the remaining with an "all ones" mask (if you have a binary number like 0010000, subtracting one results 0001111 - the same number of 1s as you had 0-s in the original number).

    For the bottom it's the same, just don't have to care with the initial shifting.

    top = (42 >> 3) & ((1 << 5) - 1) = 5 & (32 - 1) = 5 = 00101b
    bottom = 42 & ((1 << 3) - 1) = 42 & (8 - 1) = 2 = 010b
    

提交回复
热议问题