bit-shifting by an integer value

浪子不回头ぞ 提交于 2019-12-02 00:47:00

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.

Duc Vo

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