I have a 14 bits address with leading zeros and I want to divide it into page number and offset. I was trying to solve it with shifting the address but my offset is getting wrong value, however the page number shows up correctly. Can you point where I am wrong here?
Page numbers bits are [2:5] Offset bits are [6:15]
struct Mem
{
unsigned int address = 0x0000;
unsigned int pageNum = 0x0;
unsigned int pageOff = 0x000;
}
int main()
{
Mem box;
box.address = 0x0ad0;
box.pageNum = (box.address << 2) >> 12;
box.pageOff = (box.address << 6) >> 6;
return 0;
}
Shifting left to clear out digits is a dangerous game, in my opinion, because if you happen to be using
intinstead ofunsigned int, you might get a sign extend you didn't intend. I recommend shifting and masking:If your address looks like this:
Where
Pis page numbers andOis offsets then you would do:However, as Remy pointed out you could just use bit fields (https://en.cppreference.com/w/c/language/bit_field) like: