How to do Bit masking in C++?

IkarusDowned

Junior Member
Oct 21, 2005
15
0
0
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!
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126

// 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
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
// 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;
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
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