【发布时间】:2018-10-01 11:52:16
【问题描述】:
我有五个短类型变量,我想将它们连接成一个 32 位 unsigned int 类型。我需要连接五个短变量。这些变量的名称称为 opcode(5 位)、reg1(4 位)、reg2(4 位)、reg3(4 位)、extension(3 位)和 addr_constant(12 位)。现在我的代码不适用于我不知道为什么的一种情况。我在下面列出了我的代码。
这段代码的目的是将某些值转换为 32 位机器指令,这意味着即使我得到了等价的值,我仍然需要一个 32 位指令。
...
unsigned int *const word;
unsigned short opcode = 1;
unsigned short reg1 = 3;
unsigned short reg2 = 4;
unsigned short reg3 = 5;
unsigned short extension = 0;
unsigned int addr_constant = 0;
unsigned int machine_word = 0;
machine_word = machine_word | (opcode << 27);
machine_word = machine_word | (reg1 << 23);
machine_word = machine_word | (reg2 << 19);
machine_word = machine_word | (reg3 << 15);
machine_word = machine_word | (extension << 12);
machine_word = machine_word | addr_constant;
*word = machine_word
return 0;
...
二进制形式的输出应该是:
0000 1001 1010 0010 1000 0000 0000 0000.
但现在是:
1001 1010 0010 1000 0000 0000 0000.
如您所见,它遗漏了前 4 个零。
在下面的测试中,“word”是:unsigned int *const word。在上面代码的最后,我写了“*word = machine_word”。在测试中,它比较:“word == 0x09a28000” 我没有通过以下测试。
assert(word == 0x09a28000);
【问题讨论】:
-
printf("%d\n", machine_word);不可能打印1001 1010 0010 1000 0000 0000 0000。请显示执行打印的代码。 -
0000 1001 1010 0010 1000 0000 0000 0000与1001 1010 0010 1000 0000 0000 0000.相同,就像02与2相同。 -
测试是怎么写的?那么
printf("%08x\n", machine_word)的输出是什么? -
“我在
assert(word == 0x09a28000);上失败了” - 可能是因为word与machine_word不一样???? -
您的代码有效,请参阅here 以获取实时版本。
标签: c bit-manipulation bitwise-operators bit-shift bitwise-or