要在C中签名int的字节 [英] Byte to signed int in C

查看:60
本文介绍了要在C中签名int的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中的一个char中存储了一个二进制值,我想将此字节转换为C中的有符号int. 目前我有这样的东西:

I have a binary value stored in a char in C, I want transform this byte into signed int in C. Currently I have something like this:

char a = 0xff;
int b = a; 
printf("value of b: %d\n", b);

标准输出的结果将为"255",所需的输出为"-1".

The result in standard output will be "255", the desired output is "-1".

推荐答案

替换:

char a = 0xff

通过

signed char a = 0xff;  // or more explicit: = -1

printf打印-1.

如果您不想更改a的类型,请在注释中添加@veer,只需将a强制转换为(signed char),然后将其值分配给b.

If you don't want to change the type of a, as @veer added in the comments you can simply cast a to (signed char) before assigning its value to b.

请注意,在这两种情况下,此整数转换都是实现定义的,但这是常见的实现定义的行为.

Note that in both cases, this integer conversion is implementation-defined but this is the commonly seen implementation-defined behavior.

这篇关于要在C中签名int的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆