Sign in to follow this  
RandomAxess

Bit masking in C++?

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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);




?

Share this post


Link to post
Share on other sites
Alternately, you could make life a lot easier for yourself in the future and learn hexadecimal, making it very easy to mask out bits manually [grin] But the solutions presented here are perfectly good as well, if a little bit on the 'apply a hack now to avoid solving the real problem' side.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this