在c中将128分配给char变量 [英] assigning 128 to char variable in c
问题描述
输出结果是128的32位2的补码,即4294967168。如何?
#include< stdio.h>
int main()
{
char a;
a = 128;
if(a ==-128)
{
printf(%u\n,a);
}
返回0;
}
编译带有警告的代码给出:
警告:从'int'转换为'char'的溢出将值从'128'更改为'-128'[-Woverflow ]
,告诉您分配 a = 128;
不是
标准说:
6.3.1.3有符号和无符号整数
1将整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新类型表示,则该值不变。
2否则,如果新类型是无符号的,则通过重复添加或减去新类型可以表示的最大值,直到该值在新类型的范围内,来转换该值。
3否则,将对新类型进行签名,并且无法在其中表示值; 结果是实现定义的,还是引发了实现定义的信号。
所以我们不知道这是什么
但是,如果我们做一些猜测(注意这只是一个猜测):
128作为8位将是0b1000.0000
因此,当您调用 printf
时,会转换为 int
会有一个符号扩展名,例如:
0b1000.0000 ==> 0b1111.1111.1111.1111.1111.1111.1000.0000
其中-打印为无符号代表数字4294967168
The output comes to be the 32-bit 2's complement of 128 that is 4294967168. How?
#include <stdio.h>
int main()
{
char a;
a=128;
if(a==-128)
{
printf("%u\n",a);
}
return 0;
}
Compiling your code with warnings turned on gives:
warning: overflow in conversion from 'int' to 'char' changes value from '128' to '-128' [-Woverflow]
which tell you that the assignment a=128;
isn't well defined on your plat form.
The standard say:
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
So we can't know what is going on as it depends on your system.
However, if we do some guessing (and note this is just a guess):
128 as 8 bit would be 0b1000.0000
so when you call printf
where you get a conversion to int
there will be a sign extension like:
0b1000.0000 ==> 0b1111.1111.1111.1111.1111.1111.1000.0000
which - printed as unsigned represents the number 4294967168
这篇关于在c中将128分配给char变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!