In: Computer Science
1) If c is type char and i type int, what is assigned to c and i? Give answers in hex. Assume c is one byte, and i is four bytes. Explain. c = 240; i = c; 2) If c is type unsigned char and i type int, what is assigned to c and i? Give answers in hex. Explain c = 240; i = c; 3) If c is type signed char and i type int, what is assigned to c and i? Give answers in hex. Explain c = 240; i = c;
explanation:-
as we know
Type | Storage size | Value range |
---|---|---|
char | 1 byte | -128 to 127 or 0 to 255 |
unsigned char | 1 byte | 0 to 255 |
signed char | 1 byte | -128 to 127 |
The first bit is the sign-bit, leaving us with 11110000. Per two's complement, if we complement it (getting 00001111), and then add one, we get 00010000 -- this is 16. As our starting point, 240 = F0 in hex, and 11110000 in binary.
When it converts the signed char to signed int, it doesn't say "this would be 240 if it's unsigned", it says "this is -16, make it an int of -16", for which the 32-bit two's complement representation is FFFFFFF0, because it must be the negative value for the full size of int (this is called sign-extension):
+36 as a 32-bit value: 000000000000000000000000 11110000 complement: 111111111111111111111111 00001111 add one: 111111111111111111111111 00010000
Or, in hex, FFFFFFF0.
This is why you must be careful with printf("%x", c); (and relatives) -- if you intend to just get a two-digit value, and chars are signed, you may wind up with eight digits instead. Always specify "unsigned char" if you need it to be unsigned
#include <stdio.h>
int main()
{
char c=240;
int i=c;
printf("c : HEX: = %X",c);
printf("\ni : HEX: = %X",i);
return 0;
}
output:
c :HEX: =fffffff0
c :HEX: =fffffff0
#include <stdio.h>
int main()
{
unsigned char c=240;
int i=c;
printf("c : HEX: = %X",c);
printf("\ni : HEX: = %X",i);
return 0;
}
output:
c :HEX: =f0
c :HEX: =f0
#include <stdio.h>
int main()
{
signed char c=240;
int i=c;
printf("c : HEX: = %X",c);
printf("\ni : HEX: = %X",i);
return 0;
}
output:
c :HEX: =fffffff0
c :HEX: =fffffff0