比特移位一个整数值 [英] bit-shifting by an integer value
问题描述
这code是用于高速缓存模拟器项目 - 我想从一个内存地址中提取一定位。当我尝试使用INT变量做位转移,我结束了不正确的结果,但是当我直接使用数字,我的结果是正确的。我一直在到处找一个答案,但我不能找到一个。这里有什么是我的问题?
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 an incorrect result, but when I use the numbers directly, my result is correct. I've been looking all over for an answer to this, but I can't find one. What is my issue here?
#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 tag1 = (mem_addr&(((1<<33)-1)<<(2+5+8)))>>(2+5+8);
unsigned long long int tag2 = (mem_addr&(((1<<tag_bits)-1)<<(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);
}
输出是:
Tag 1: fffeb509
Tag 2: 1
我也越来越为正确计算TAG1的线,这是没有道理给我一个警告,因为Tag1是一个64位无符号长的长整型,而我只有48位转移:
I am also getting a warning for the line that computes tag1 correctly, which doesn't make sense to me, since tag1 is a 64-bit unsigned long long int, and I am only shifting by 48 bits:
warning: left shift count >= width of type [enabled by default]
在此先感谢您的帮助。
Thanks in advance for the help.
推荐答案
所有整数文字值 INT
类型,除非你指定了preFIX诸如例如 1ULL
。
All integer literal values are int
type, unless you specify a prefix such as e.g. 1ULL
.
这意味着 1 LT;γ-33
移32位有符号值33的步骤。你需要做的 1ULL&LT;&LT; 33
。
That means that 1<<33
shifts a 32-bit signed value 33 steps. You need to do 1ULL << 33
.
这篇关于比特移位一个整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!