无符号转换为字符符号整数 [英] Converting unsigned chars to signed integer
本文介绍了无符号转换为字符符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个元素的重新presents有符号整数无符号的字符数组。我怎样才能将这些2个字节为一个有符号整数?
I have an unsigned char array with 2 elements that represents a signed integer. How can I convert these 2 bytes into a signed integer?
修改:无符号的字符数组是小尾数
Edit: The unsigned char array is in little endian
推荐答案
有关最大的安全性,使用
For maximum safety, use
int i = *(signed char *)(&c[0]);
i *= 1 << CHAR_BIT;
i |= c[1];
有关大端。交换 C [0]
和 C [1]
为小尾数。
for big endian. Swap c[0]
and c[1]
for little endian.
(说明:我们之间的preT在 c中的字节[0]
为符号字符
,然后在移植的方式算术左移,然后加入 C [1]
)
(Explanation: we interpret the byte at c[0]
as a signed char
, then arithmetically left shift it in a portable way, then add in c[1]
.)
这篇关于无符号转换为字符符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文