samedi 5 avril 2014

c - suis j'extraire ces champs correctement à l'aide de décalage de bits ? (tag, index, offset) - Stack Overflow


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!




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;


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!



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;

0 commentaires:

Enregistrer un commentaire