0

我在 C 中的基本概念方面遇到了一些挑战。非常有必要提供帮助。我继续并用代码的解释以及我试图在那里提出的问题对代码进行了注释。

void main (void)
{
  printf("%x", (unsigned)((char) (0x0FF))); //I want to store just 0xFF;
  /* Purpose of the next if-statement is to check if the unsigned char which is 255
   * be the same as the unsigned int which is also 255. How come the console doesn't print
   * out "sup"? Ideally it is supposed to print "sup" since 0xFF==0x000000FF.
   */
  if(((unsigned)(char) (0x0FF))==((int)(0x000000FF))) 
     printf("%s","sup");
}

谢谢您的帮助。

4

1 回答 1

8

你把括号弄错了,

if(((unsigned)(char) (0x0FF))==((int)(0x000000FF))) 

对左操作数执行两次强制转换,首先是char,通常(1)导致 -1,然后将该值强制转换为unsigned int,通常(2)导致 2^32-1 = 4294967295。

(1)如果char是有符号的,8 位宽,使用二进制补码,并且只取最低有效字节即可完成转换,这与大多数托管实现的情况一样。如果char是无符号的,或宽于 8 位,则结果将为 255。

(2)如果转换为char-1 并且unsigned int是 32 位宽。

于 2012-09-23T18:40:13.793 回答