我对这些转变有错吗?

问题描述

我有一个带前导零的 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

但是,正如 Remy 指出的那样,您可以只使用位字段 (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