Grabbing n bits from a byte

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

    Integers are represented inside a machine as a sequence of bits; fortunately for us humans, programming languages provide a mechanism to show us these numbers in decimal (or hexadecimal), but that does not alter their internal representation.

    You should revise the bitwise operators &, |, ^ and ~ as well as the shift operators << and >>, which will help you understand how to solve problems like this.

    The last 3 bits of the integer are:

    x & 0x7
    

    The five bits starting from the eight-last bit are:

    x >> 3    // all but the last three bits
      &  0x1F // the last five bits.
    

提交回复
热议问题