user1871869 - 6 months ago 60

C Question

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 like this: 0010 1010. How would I grab the first 5 bits which are 00101 and the next 3 bits which are 010, and place them into separate integers?

If anyone could help me that would be great! I know how to extract from one byte which is to simply do

`int x = (number >> (8*n)) & 0xff // n being the # byte`

which I saw on another post on stack overflow, but I wasn't sure on how to get separate bits out of the byte. If anyone could help me out, that'd be great! Thanks!

Answer

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.
```