未如预期一个简单的C程序的输出 [英] A simple C program output is not as expected
问题描述
我在做这个简单的程序和我的脑海里卡住了。
#包括LT&;&stdio.h中GT; 诠释的main()
{
int类型的签署;
符号字符℃;
unsigned char型B:
B = 0xF4中;
A =(签字)B: // 1)这个任务应该是相同的
C =(签字)B:
的printf(%d个\\ N,一);
一个= C; // 2)这一个
的printf(%d个\\ N,一);
返回0;
}一个= 244,A = -12
我试过,以确保任务是顺利,因为它可以,但我得到两个不同的答案,我希望无论是作为-12。什么小东西我丢失?
有关问题是
{
B = 0xF4中;
C = 0xF4中;
A =(符号的int)B: //试图挽救迹象,但得到244
的printf(%d个\\ N,一);
一个= C; // SIGN保存在这里,并得到-3
的printf(%d个,一);
}
244,-3
所以我想从unsigned char类型保存迹象。这是可能以这种方式?
符号字符℃;
unsigned char型B:
B = 0xF4中; / * ... * / C =(签字)B:
乙
的值是 0xF4中
( 244
),但 C
键入(符号字符
)只能容纳 -128 $之间的值C $ C>和
127
(在你的实现)。因此,当 244
分配给 C
,先把它转化为符号字符
和C表示这个整数的转换是实现定义。 GCC
为大多数实现
只是环绕模 256
,这就是为什么的ç
值为 -12
。
下面是 GCC
文件:
http://gcc.gnu.org/onlinedocs/gcc/Integers- implementation.html
对于转换的类型的宽度N的值减小模2 ^ N至是内的类型的范围
块引用>I was doing this simple program and my mind got stuck
#include<stdio.h> int main() { signed int a; signed char c; unsigned char b; b = 0xf4; a = (signed)b; // 1)this assignment should be same c = (signed)b; printf("%d\n",a); a = c; // 2)as this one printf("%d \n",a); return 0; } a = 244, a = -12
I tried to make sure that assignment is as smooth as it can be but I am getting two different answers and I expected both as -12. What small thing I am missing?
The relevant question was
{ b = 0xf4; c = 0xf4; a = (signed int)b; //trying to save sign but get 244 printf("%d\n", a); a = c; //sign saved here and got -3 printf("%d", a); }
244, -3
so i am trying to save the sign from an unsigned char. Is this possible in this manner?
解决方案signed char c; unsigned char b; b = 0xf4; /* ... */ c = (signed)b;
The value of
b
is0xf4
(244
) butc
type (signed char
) can only hold values between-128
and127
(in your implementation). So when244
is assigned toc
it is first converted tosigned char
and C says this integer conversion is implementation defined.gcc
as most implementations just wraps around modulo256
and that's why the value ofc
is-12
.Here is
gcc
documentation:http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html
"For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type"
这篇关于未如预期一个简单的C程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!