Bit masking in C++?

Started by
11 comments, last by RandomAxess 18 years, 5 months ago
So, i want to mask a certain number of bits in, say, an integer. How do i do that using another integer variable? Like, i want to mask the number of bits in int bit_mask and i was to mask the value int masked_number. I haven't found a good explaination or anything on how to do that. please help!
Advertisement
Hey bud,

int value;int mask;int output;output = value & mask;


Hope that helps,

ace
i just ran that with the follownig values:

int mask = 4;
int value = 1023;

int output = value & mask;

printf("output: %d\n", output);

i got the value 4 out. To be more specific, i want to take the bit string that is 1023: 1111111111 and mask the right 4-most bits, so the 1111. i want the rest of the values to be 0's. so it should be: 0000001111. how do i do that?
Your mask needs to be the value with the bottom 4 bits set and the rest clear, i.e. 0xf.
4 != 1111b

1111b = 15

good luck
0000001111111111 (bin) = 1023 (dec)
0000000000001111 (bin) = 15 (dec)

Then do what ace_lovegrove suggested, but instead of taking
the integer number '4' (which is 100 binary), use the binary
00001111 and convert it to an decimal number = 15.

So Output = 1023 & 15 = 15 dec = 0xF (hex)

Regards
visit my website at www.kalmiya.com
ok, here's the actual situation i need to figure out, which is giving me problems:

I need to make a function that will accept two int values. One is the size of the mask, AKA the number of bits i want to mask, and then the value i'm masking. Whats a good solution to this? I don't want to do a bunch of bit shifting in a loop to make the mask, i imagine there's a better way to do it?
Imagine you want to mask off the bottom 4 bits. Then the mask you need to use is 00001111b, which equals 00010000b - 1. Thus, a function to generate the mask should be:

int MakeMask(int numBits){    return (1 << (numBits + 1)) - 1;}
Shouldn't it just be:

int MakeMask(int numBits)
{
return ((1 << numBits) - 1);
}

1 << 4 = 16 - 1 = 15 = 1111b

int value;int output;int Mask(int numBits){return ((1 << numBits) - 1);}output = value & Mask(4);


?
Yep, you're right...

This topic is closed to new replies.

Advertisement