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.
You have gotten your parentheses wrong,
performs two casts on the left operand, first to
char, usually(1) resulting in -1, and then that value is cast tounsigned int, usually(2) resulting in 2^32-1 = 4294967295.(1) If
charis 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. Ifcharis unsigned, or wider than eight bits, the result will be 255.(2) If the cast to
charresulted in -1 andunsigned intis 32 bits wide.