将无符号字符转换为有符号整数

发布于 2024-10-14 13:59:18 字数 109 浏览 8 评论 0原文

我有一个 unsigned char 数组,其中有 2 个元素代表有符号整数。如何将这 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

醉城メ夜风 2024-10-21 13:59:18

为了获得最大的安全性,请使用

int i = *(signed char *)(&c[0]);
i *= 1 << CHAR_BIT;
i |= c[1];

大尾数法。将 c[0]c[1] 交换为小端。

(说明:我们将 c[0] 处的字节解释为 signed char,然后以可移植的方式对其进行算术左移,然后添加到 c[1 ]。)

For maximum safety, use

int i = *(signed char *)(&c[0]);
i *= 1 << CHAR_BIT;
i |= c[1];

for big endian. Swap c[0] and c[1] for little endian.

(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].)

你与清晨阳光 2024-10-21 13:59:18

将它们包装在一个联合中:

union {
  unsigned char a[2];
  int16_t smt;
} number;

现在填充数组后,您可以将其用作 number.smt

wrap them up in a union:

union {
  unsigned char a[2];
  int16_t smt;
} number;

Now after filling the array you can use this as number.smt

鼻尖触碰 2024-10-21 13:59:18

这取决于字节序。
适用于大端字节序的内容:

unsigned char x[2];
short y = (x[0] << 8) | x[1]

适用于小端字节序的内容:

unsigned char x[2];
short y = (x[1] << 8) | x[0]

It depend of endianness.
Something for big endian :

unsigned char x[2];
short y = (x[0] << 8) | x[1]

Something for little endian :

unsigned char x[2];
short y = (x[1] << 8) | x[0]
几度春秋 2024-10-21 13:59:18

可移植的解决方案:

unsigned char c[2];
long tmp;
int result;

tmp = (long)c[0] << 8 | c[1];
if (tmp < 32768)
    result = tmp;
else
    result = tmp - 65536;

假设数组中的字节表示 16 位、二进制补码、大端有符号整数。如果它们是小端整数,只需交换c[1]c[0]即可。

(在极不可能的情况下,它是补码,请使用 65535 而不是 65536 作为要减去的值。符号大小留给读者作为练习; )

The portable solution:

unsigned char c[2];
long tmp;
int result;

tmp = (long)c[0] << 8 | c[1];
if (tmp < 32768)
    result = tmp;
else
    result = tmp - 65536;

This assumes that the bytes in the array represent a 16 bit, two's complement, big endian signed integer. If they are a little endian integer, just swap c[1] and c[0].

(In the highly unlikely case that it is ones' complement, use 65535 instead of 65536 as the value to subtract. Sign-magnitude is left as an exercise for the reader ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文