This code is for a cache simulator project - I am trying to extract certain bits from a memory address. When I attempt to use int variables to do the bit shifting, I end up with
All integer literal values are int
type, unless you specify a prefix such as e.g. 1ULL
.
That means that 1<<33
shifts a 32-bit signed value 33 steps. You need to do 1ULL << 33
.
I think the problem is: constant 1 is casting to integer type (4 bytes 32 bits). However, you do shift left 33 bits (exceed integer type), in this case we should cast 1 to unsigned long long int (8 bytes = 64 bits) before doing shift left:
#include <stdio.h>
void main(){
unsigned long long int mem_addr = 0x7fff5a8487c0;
int byte_offset_bits = 2;
int block_offset_bits = 5;
int index_bits = 8;
int tag_bits = 33;
unsigned long long int one = 1;
unsigned long long int tag1 = (mem_addr&(((one<<33)-one)<<(2+5+8)))>>(2+5+8);
unsigned long long int tag2 = (mem_addr&(((one<<tag_bits)-one)<<(byte_offset_bits + block_offset_bits + index_bits)))>>(byte_offset_bits + block_offset_bits + index_bits);
printf("%s %llx\n", "Tag 1:", tag1);
printf("%s %llx\n", "Tag 2:", tag2);