我是否使用按位移位正确提取这些字段? (标签、索引、偏移量)

发布于 2024-12-15 23:16:52 字数 652 浏览 2 评论 0原文

我正在用 C 语言构建一个 CPU 缓存模拟器。我希望你能告诉我是否正确提取了这些字段:

32 位地址 应该分解如下:

+---------------------------------------------------+
| tag (20 bits) | index (10 bits) | offset (2 bits) |
+---------------------------------------------------+

这是我要获取的代码每个人的价值观:

void extract_fields(unsigned int address){

   unsigned int tag, index, offset;

   // Extract tag
   tag = address >> 12;

   // Extract index
   index = address << 20;
   index = index >> 22;

   // Extract offset
   offset = address << 30;
   offset = offset >> 30;

}

非常感谢任何建议!

I am building a CPU cache emulator in C. I was hoping you could tell me if I am extracting these fields correctly:

The 32-bit address should be broken up as follows:

+---------------------------------------------------+
| tag (20 bits) | index (10 bits) | offset (2 bits) |
+---------------------------------------------------+

Here is my code to obtain the values for each:

void extract_fields(unsigned int address){

   unsigned int tag, index, offset;

   // Extract tag
   tag = address >> 12;

   // Extract index
   index = address << 20;
   index = index >> 22;

   // Extract offset
   offset = address << 30;
   offset = offset >> 30;

}

Any advice is much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅笑依然 2024-12-22 23:16:52

看起来您的解决方案有效,但它通常以不同的方式完成,可能更清晰一些。

对于你的例子:

// Shift off the lowest 12 bits, and mask off the higher ones
tag = (address >> 12) & 0xFFFFF; 

// Shift off the lowest 2 bits, and mask off the higher ones
index = (address >> 2) & 0x3FF;

// Shift off the lowest 0 bits, and mask off the higher ones
offset = (address >> 0) & 0x3;

It looks like your solution works, but it is often done a different way that is probably a bit more clear.

For your example:

// Shift off the lowest 12 bits, and mask off the higher ones
tag = (address >> 12) & 0xFFFFF; 

// Shift off the lowest 2 bits, and mask off the higher ones
index = (address >> 2) & 0x3FF;

// Shift off the lowest 0 bits, and mask off the higher ones
offset = (address >> 0) & 0x3;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文