我有 2 个字节需要转换为带符号的短数字。例如,我有单独的二进制字节(0000 0001)和(0000 0002)。如何将它们转换为带符号的短值?
最佳答案
如果字节以有符号数据类型保存,例如 signed char
或 int8_t
,那么就非常简单:
signed short combine_signed(signed char byte1, signed char byte2) {
return byte1 * 256 + (uint8_t)byte2;
}
这里使用乘法,而不是移位运算,但预计编译器实际上会插入适当的移位运算。 C 标准没有规定左移负数的结果,因此左移不能在可移植代码中使用。
如果字节是无符号类型或宽于8位的类型,那么最简单的方法是先将高位字节转换为有符号值,然后按上述方法进行。不能通过简单的强制转换来转换为有符号值,因为这样的转换将导致整数溢出,其结果未由 C 标准指定。因此,可移植程序必须显式测试高位:
signed short combine(int byte1, int byte2) {
// This code assumes that byte1 is in range, but allows for the possibility
// that the values were originally in a signed char and so is now negative.
if (byte1 >= 128) byte1 -= 256;
return byte1 * 256 + (uint8_t)byte2;
}
(用于 x86 的 gcc 和 clang,使用 -O2 或更好的编译器,设法将其简化为简单的三指令序列,无需乘法或条件。)
关于c - 如何在 C 中将 2 个字节转换为有符号短整型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56716457/