c - 如何检索存储在无符号变量中的有符号值

标签 c integer embedded type-conversion

我有一个带符号的 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):

  1. 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.
  2. ...
  3. 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/

相关文章:

c++ - 检查数字是否达到阈值

java - Java 如何处理溢出整数

android - Android 是否推荐用于 Atom 处理器平台?

c - 如何通过选择 c 中的行和列来查找二维数组的子集?

c - 在父进程中运行单独的进程

c# - 编码(marshal)包含可变长度数组的 C 结构

c - 非零 TCP 窗口比例选项的原因

bash - bash shell 是否将 "fact=2"这样的赋值视为整数或长整型?

linux - 检测堆栈溢出

c - C赋值中奇怪的反斜杠运算符