本文介绍了我是否使用按位移位正确提取了这些字段? (标签,索引,偏移量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用C语言构建一个CPU缓存模拟器.我希望您能告诉我是否正确提取了这些字段:
I am building a CPU cache emulator in C. I was hoping you could tell me if I am extracting these fields correctly:
32位地址应按以下方式分解:
+---------------------------------------------------+
| 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;
}
任何建议都非常感谢!
推荐答案
看起来您的解决方案可以工作,但是通常以不同的方式完成,可能会更清楚.
It looks like your solution works, but it is often done a different way that is probably a bit more clear.
以您的示例为例:
// 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;
这篇关于我是否使用按位移位正确提取了这些字段? (标签,索引,偏移量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!