我有一个带符号的 8 位值(二进制补码)存储在一个无符号的 uint8_t 变量中。 发生这种情况是因为值是通过 spi 接口(interface)从外部外围设备读取的,例如:
uint8_t return_value = read_spi(uint8_t register_address)
外设的数据表说该特定地址包含一个二进制补码值,因此 return_value 中的位模式应该是一个带符号的 8 位值。
我知道检索带符号值的明显方法:去掉符号位,如果负翻转位,加 1,乘以 -1。
我想知道是否有更优雅的方式。
最佳答案
如果您使用二进制补码系统,您可以这样做:
int8_t result = return_value; // or assign the from function directly
严格来说,当值为负时,行为是实现定义的(N1570,6.3.1.3):
- When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
- ...
- Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
在实践中,它只是有效; intN_t
类型保证是二进制补码且没有填充位。典型的现代机器不会对无符号到有符号的赋值执行任何额外的操作,而只是复制这些位。如果您想确定,请查看您的编译器手册。
关于c - 如何检索存储在无符号变量中的有符号值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721026/