Am I extracting these fields correctly using bitwise shift? (tag, index, offset)

纵饮孤独 提交于 2019-12-24 09:33:37

问题


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!


回答1:


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;


来源:https://stackoverflow.com/questions/8145346/am-i-extracting-these-fields-correctly-using-bitwise-shift-tag-index-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!