• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

How to do Bit masking in C++?

IkarusDowned

Junior Member
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!
 

// use xor instead of and to clear bits instead of keep bits

int x = v & 0x00f ; // mask to only inlcude lower 4

int x = v & (1 << k) ; // mask just single bit k,, k = 0-31 for int

int x = v & ((1 << n)-1) ; // retain lower n bits, n = 1-32 NOT 0-1
 
// use xor instead of and to clear bits instead of keep bits
That's only if you know for sure the bit is already set. The easiest way is just to and with the bitwise inverse...

//clear lowest bit
int x = v & ~0x1;

//set lowest bit
int x = v | 0x1;
 
Originally posted by: CTho9305
That's only if you know for sure the bit is already set. The easiest way is just to and with the bitwise inverse...
d'oh! correct. AND to keep, OR to set, AND of inverse to clear.

to clear bits

int x = v & ~ (the bits to clear)

such as

int x = v & ~ (1 << k) ; // clear bit k where k = 0 - 31
 
Back
Top