-1

I'm pretty new to C and I seem to be messing up my bitmasking. From what I understand, it's a way to grab or create something of a subset from a binary value.

Say I want to grab the last 8 bits of an unsigned int value, containing 00001111000011110000111100001111.

How would I use AND/OR to grab those last 8?

4 Answers4

2

Here's a more general solution to generate the mask based on how many bits you're interested int.

unsigned int last_n_bits(unsigned int value, int n)
{
    unsigned int mask = -1;
    if (n < sizeof(unsigned) * CHAR_BIT)
        mask = ((1<<n)-1);
    return value & mask;
}
cleblanc
  • 3,678
  • 1
  • 13
  • 16
0

You can use the BINARY AND operator for do a binary mask:

unsigned char last_eight_bits = my_number & 0b11111111
iElden
  • 1,272
  • 1
  • 13
  • 26
  • 2
    No need for the bit operation if the target is a `char` (or another type that is (usually) 8 bits wide). Also 8 times 1 is harder to count than two times f. – Swordfish Nov 19 '18 at 17:45
0

Mask-out all bits > 0xff:

value & 0xffu
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • Or create a mask using `(1 << 8) - 1` where 8 represents the number of bits to grab (beware not to exceed the size of the integer, of course). – Maarten Bodewes Nov 19 '18 at 17:50
0

Say I want to grab the last 8 bits of an unsigned int value, containing 00001111000011110000111100001111.

How would I use AND/OR to grab those last 8?

In this case, you would use AND. The following code will grab the 8 least significant bits:

unsigned int number = 0x0F0F0F0Fu;
unsigned int mask = 0x000000FFu; // set all bits to "1" which you want to grab
unsigned int result = number & mask; // result will be 0x0000000F

The &-Operator is used for an AND-Operation with each bit:

    00001111000011110000111100001111
AND 00000000000000000000000011111111
------------------------------------
    00000000000000000000000000001111

Be aware that "0 AND X = 0" and that "1 AND X = X". You can do further investigation at: https://en.wikipedia.org/wiki/Boolean_algebra.

Community
  • 1
  • 1