bit-shifting by an integer value

前端 未结 2 1916
太阳男子
太阳男子 2021-01-21 12:42

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

2条回答
  •  温柔的废话
    2021-01-21 13:47

    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 
    
    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<>(byte_offset_bits + block_offset_bits + index_bits);
    
        printf("%s %llx\n", "Tag 1:", tag1);
        printf("%s %llx\n", "Tag 2:", tag2);
    

提交回复
热议问题