c中的位移位返回错误的结果

时间:2015-02-07 18:04:10

标签: c bit-manipulation machine-code

我正在编写代码来翻译机器代码。 readFiveBytes位于一个循环内部,并且一次占用一个字节并将每个字节放入正确的位置并最后返回一个地址。

void readFiveBytes(int c) {
    if (counter != 0) {
        currentIns = currentIns | (c << (counter * 4));
        printf("reading byte: %X; address: %08X; counter: %d; type: 5\n",c, currentIns, counter);
        counter = counter - 2;
    } else {
        currentIns = currentIns | c;
        printType3(currentIns);
        printf("reading byte: %X; address: %08X; counter: %d; type: 5\n",c, currentIns, counter);
        currentIns = 0x00000000000000;
        isFinishReading = true;
    }
}   

输出

reading byte: 71; address: 00000071; counter: 8; type: 5
reading byte: 26; address: 26000071; counter: 6; type: 5
reading byte: 0; address: 26000071; counter: 4; type: 5
reading byte: 0; address: 26000071; counter: 2; type: 5
reading byte: 0; address: 26000071; counter: 0; type: 5 

我想知道为什么第一个字节没有转移到最左边? (看起来第二个效果很好)

1 个答案:

答案 0 :(得分:1)

移动位宽或更大是未定义的行为。

第一次传递,counter = 8尝试currentIns = currentIns | (c << 32);。假设currentIns是32位整数,这是未定义的行为。

在这种情况下,典型的未定义行为仅发生(counter * 4)%32的转变。使用counter = 8,这是0的转变。

相关问题