c语言中 等号是如何运作的?

unsigned char c=-1;

-1是按照int类型存储的常量吧 打印出来的c是直接把-1的补码模式的最后一个字节直接抄给c了 c语言的等号就是直接按位照抄么? 把常量赋予变量的时候会不会对常量先转化某种与变量比较搭配的类型再赋予?

阅读 2.8k
1 个回答

ISO C 标准中写到

6.3.1.3 Signed and unsigned integers

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. 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. 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.

换句话说,unsigned char 的表示范围是 [0, 255],不能表示 -1,于是将 -1 加上 256 得到 255。

如果是把 signed char 型 -1 转成 unsigned int,则用 -1 加上 4294967296 得到 4294967295。

对硬件来说,从有符号到无符号的转换就是简单地在前面补符号位或者直接截断。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题