将有符号字符读取为无符号 - 类型提升
考虑这个小程序:
#include <stdio.h>
int main()
{
char c = 0xFF;
printf("%d\n", c);
return 0;
}
它的输出是 -1
,正如预期的那样(考虑到 char
在我的 系统)。我想做的是让它打印255
。这是属于 当然是真实情况的简化,我不能仅仅定义 c
为无符号。
第一个可能的更改是使用 %u
作为格式化程序,但是 通常的类型提升规则适用于此,并且数字打印为 232 - 1.
那么有没有什么方法可以将签名字符读取为无符号之前 提升为 int?我可以创建一个指向无符号字符集的指针 c
的地址,稍后取消引用它,但不确定这是否是最好的 方法。
Consider this little program:
#include <stdio.h>
int main()
{
char c = 0xFF;
printf("%d\n", c);
return 0;
}
Its output is -1
, as expected (considering char
is signed in my
system). What I'm trying to do is to make it print 255
. This is of
course a simplification of the real situation, where I can't just definec
as unsigned.
The first possible change would be using %u
as formatter instead, but
the usual type promotion rules apply here, and the number is printed as
232 - 1.
So is there any way to read the signed char as unsigned before it gets
promoted to an int? I could create a pointer to a unsigned char set to the
address of c
, and dereference it later, but not sure if this is the best
approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
c
正在使用签名的升级规则进行升级。将c
强制转换为 unsigned 以使用无符号提升。unsigned char 将提升为 unsigned int。
c
is being promoted using signed promotion rules. Castc
to unsigned to use unsigned promotion.Unsigned char will be promoted to unsigned int.