Mathew Kurian
Mathew Kurian

Reputation: 6039

Storing Variable in C

I am having some challenges with a basic concept in C. Help would be much obliged. I went ahead and annotated the code with the explanation of the code as well the question I am trying to ask there as well.

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");
}

Thank you for your help.

Upvotes: 0

Views: 140

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183868

You have gotten your parentheses wrong,

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

performs two casts on the left operand, first to char, usually(1) resulting in -1, and then that value is cast to unsigned int, usually(2) resulting in 2^32-1 = 4294967295.

(1) If char is signed, eight bits wide, two's complement is used and the conversion is done by just taking the least significant byte, as is the case for the majority of hosted implementations. If char is unsigned, or wider than eight bits, the result will be 255.

(2) If the cast to char resulted in -1 and unsigned int is 32 bits wide.

Upvotes: 8

Related Questions