我目前正在编写一个涉及二进制内存的程序,我需要一个 unsigned long long int 中的某个位序列。
现在,我目前正在循环这个代码块 4 次以尝试创建一个 32 位序列。
unsigned long long int currentEntry = 0;
for (int j = 0; j < 4; ++j){
currentEntry = (currentEntry << 8);
currentEntry = (currentEntry | (unsigned long long int)entryBuffer[i][j]);
}
entrybuffer[i][j] 是一个 char,它包含一个字节值,我将它转换为一个 unsigned long long int,据我所知,它似乎正在工作,直到我遇到一个奇怪的错误。例如,这里是二进制形式的 currentEntry 变量:
//goal bit sequence: 00001000000001001010000011000000
currentEntry = (currentEntry << 8);
//00000000
currentEntry = (currentEntry | (unsigned long long int)entryBuffer[i][j]); //entrybuffer[i][j] = 00001000
//00001000
currentEntry = (currentEntry << 8);
//0000100000000000
currentEntry = (currentEntry | (unsigned long long int)entryBuffer[i][j]); //entrybuffer[i][j] = 00000100
//0000100000000100
currentEntry = (currentEntry << 8);
//000010000000010000000000
currentEntry = (currentEntry | (unsigned long long int)entryBuffer[i][j]); //entrybuffer[i][j] = 10100000
//111111111111111110100000 (what?)*****
currentEntry = (currentEntry << 8);
//11111111111111111010000000000000
currentEntry = (currentEntry | (unsigned long long int)entryBuffer[i][j]); //entrybuffer[i][j] = 11000000
//11111111111111111111111111000000
我似乎在这里遗漏了一些明显的东西,我想知道是否有人可以帮助我解决这个问题。我希望代码足够有意义。
显然,按位 OR 正在改变某些东西,或者某些东西在某处溢出,这就是我将 currentEntry 设为 unsigned long long int 的原因。我显然只需要 4 个字节的存储空间,而且我知道这在机器之间会有所不同,但是我认为 unsigned long long int 足以满足我的目的。如果需要更多信息和上下文,请告诉我。
谢谢!