我错了吗



我有一个带前导零的14位地址,我想把它分成页码和偏移量。我试图通过移动地址来解决这个问题,但我的偏移量得到了错误的值,但页码显示正确。你能指出我错在哪里吗?

页码位为[2:5]偏移位为[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;
}

在我看来,向左移动以清除数字是一个危险的游戏,因为如果你碰巧使用int而不是unsigned int,你可能会得到一个你不打算的符号扩展。我建议转移和掩蔽:

如果你的地址是这样的:

X X P P P P O O O O O O O O O O

其中P是页码,O是偏移量,那么您可以这样做:

box.pageNum = (box.address >> 10) & 0xf; // 0xf is 1111 in binary, so it only keeps the right 4 binary digits
box.pageOff = box.address & 0x3ff; // 0x3ff is 1111111111 in binary, so it only keeps the right 10 digits

然而,正如雷米所指出的,你可以只使用比特字段(https://en.cppreference.com/w/c/language/bit_field)类似:

struct Address
{
unsigned int offset : 10;
unsigned int page_num : 4;
}
...
Address a;
a.page_num; // assign it directly
a.offset; // assign it directly

相关内容

最新更新