• Advertisement
Sign in to follow this  

Bit masking in C++?

This topic is 4477 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
i know Hex, but i couldn't get it to make a mask based on a variable. IE: i can't do 0xmask. if there's some trick, let me know

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement