[英]How to cast for bitwise shift
I am trying to combine bits read in different 16-bit register into a single 32-bit variable with bit shifting (this is to get an ID stored split in different register in an interesting way on a sensor).我正在尝试将不同 16 位寄存器中读取的位组合成一个带有位移的 32 位变量(这是为了在传感器上以一种有趣的方式将 ID 存储在不同的寄存器中)。
But there should have something about casting and bit shifting I am missing.但是我应该缺少一些关于铸造和位移的东西。 Especially I cannot comprehend why in the example below
sum
and id0_d + id1_d
lead to different results.特别是我无法理解为什么在下面的示例中
sum
和id0_d + id1_d
会导致不同的结果。 I would prefer a solution like the way sum
is computed without having to declare intermediate variables.我更喜欢一种解决方案,例如无需声明中间变量即可计算
sum
的方式。
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint16_t id0 = 0x4E00;
uint16_t id1 = 0xABCD;
uint32_t sum = ((uint32_t)id0)>>7 + ((uint32_t)id1)<<9;
uint32_t id0_d = ((uint32_t)id0)>>7;
uint32_t id1_d = ((uint32_t)id1)<<9;
printf("id0: %04X\n", id0);
printf("id1: %04X\n", id1);
printf("sum: %08lx\n", sum);
printf("id0_d: %08lx\n", id0_d);
printf("id1_d: %08lx\n", id1_d);
printf("id0+1_d: %08lx\n", id0_d + id1_d);
return 0;
}
Which outputs the following:输出以下内容:
id0: 4E00
id1: ABCD
sum: 00000000
^no the expected result
id0_d: 0000009c
id1_d: 01579a00
id0+1_d: 01579a9c
^expected result for "sum"
Edit the following:编辑以下内容:
uint32_t sum = ((uint32_t)id0)>>7 + ((uint32_t)id1)<<9;
uint32_t id0_d = ((uint32_t)id0)>>7;
uint32_t id1_d = ((uint32_t)id1)<<9;
to: ensure that the operations are performed in the right order:到:确保操作以正确的顺序执行:
uint32_t sum = ((uint32_t)id0>>7) | ((uint32_t)id1<<9);
uint32_t id0_d = (uint32_t)id0>>7;
uint32_t id1_d = (uint32_t)id1<<9;
Using the arithmetic operator +
in this example will produce the expected results, but with bitwise operations, the bitwise |
在此示例中使用算术运算符
+
将产生预期结果,但对于按位运算,按位|
is more commonly used比较常用
printf("id0+1_d: %08lx\n", id0_d + id1_d);
to到
printf("id0+1_d: %08lx\n", id0_d | id1_d);
This will result in the expected output:这将导致预期的 output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.