Search code examples
cbit-manipulationbitbit-shift

How do I get the MSB and LSB of a 16 bit unsigned short in C?


I'm trying to return the 10 least significant bits (while setting the 6 most significant bits to 0) and 6 most significant bits (while setting the 10 least significant bits to 0) from a 16-bit unsigned short and I'm stuck on how to accomplish this. For example, if I have an unsigned short 0x651A, then the bit representation would be:

//                MSB                               LSB
//                  +-----------+-------------------+
//                  |0 1 1 0 0 1|0 1 0 0 0 1 1 0 1 0|
//                  +-----------+-------------------+
//                  |           |                   |
//      bit offset: 16          10                  0

So, if I were to get the 6 most significant bits, then the returned short would be 0b0000000000011001. I'm very new to C and I'm still trying to understand bit management and bit shifting. Any advice or feedback is appreciated in helping me understand C better.


Solution

  • To get the least significant bits, you would use a bit mask. You apply a bitwise and to the number at hand with a mask of 10 1's in this case. The number needed can be obtained by a bitshift of 1, and then subtracting 1. That is (1 << 10)-1 in this case. So the result for any x is x & ((1 << 10)-1).

    To get the most significant bits is easier. You just shift off the lower bits, eg x >> 10