• 03-15-2009
jcafaro10
I'm writing a memory management program/simulation. Let's say I have a 32-bit pointer. I want it to represent a virtual address. Part of that address, let's say the upper 22 is the virtual page number, and the lower 10 is the page offset. How do I do bit selection in C++? How do I say something like:
int upper = upper22bits(pointer);
int lower = lower 10bits(pointer);

Thanks

I seem to remember messing around with shifts and masking but I don't really remember how.
For example if I want the upper 22 its, I think I'd right shift 10, & with enough 1's to cover the bits (2^22-1 I think) and I'd have a number represented by the upper 22 bits.
If I want the lower 10 bits I think I don't have to shift, I just & with enough 1's to cover the bits (2^10-1 I think).
I'm not sure if this is correct

I tested it out and it prints out the wrong stuff
Code:

cout << "Testing bit selection" << endl;
int test = 23; // 23 = "10111"
cout << "Lower three bits: " << (test & 2^3-1) << endl; // "111" = 7
cout << "Upper three bits: " << (test>>2 & 2^3-1) << endl; //"101" = 5

• 03-15-2009
Cactus_Hugger
Code:

2^3-1
2^3-1 is 0. However, the & will happen first (it has higher precedence that ^, see your Order of Operations)
The bigger issue, however, I suspect that ^ is not what you're expecting it to be. ^ is binary XOR, not exponent. (There is no C operator for exponent.)
• 03-15-2009
vart
Quote:

(There is no C operator for exponent.)
actually when you need power of 2 you can use C operator - shift

1<<3
• 03-15-2009
jcafaro10
Thanks, that did it