2015-02-07 62 views
-2

我在编写代码来翻译机器代码。 readFiveBytes位于一个循环内,并且一次只需要一个字节,并将每个字节放在正确的位置并最终返回一个地址。在c中移位错误返回错误结果

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 

我不知道为什么第一个字节没有被转移到最左边? (看起来像第二个工作正常)

+0

如果'counter> CHAR_BIT'怎么办? – 2015-02-07 18:05:59

+5

“位移c中工作不正常” - 得爱这些“<核心语言功能X>不工作”的问题......当然它**工作正常吗?至多*你*不能正确使用它...... – 2015-02-07 18:07:32

+2

这种类型的函数是人们说全局变量不好的原因。这个函数本身甚至没有做任何事情,它是一个已经被强制从适当位置移除的循环体,现在以一种不明显的方式通过一些全局变量进行通信,并且从外观上看,它被破坏了。不要修复这个功能,更换更好的东西。 – harold 2015-02-07 18:16:58

回答

1

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

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

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

+0

currentIns的类型是无符号的,unsigned int是32位。这就是为什么它不起作用。谢谢! – user3397656 2015-02-07 18:20:12