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);
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
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