Please help me to understand the output for the program:
int main()
{
char a = 0x99;
printf("%02x\n", a);
return 0;
}
Output:
ffffff99
Why is the output like that?
Please help me to understand the output for the program:
int main()
{
char a = 0x99;
printf("%02x\n", a);
return 0;
}
Output:
ffffff99
Why is the output like that?
There are several factors at play. For one thing, on your computer, plain char
is a signed type, not an unsigned type. For another, arguments to a variadic function like printf()
undergo integer promotion rules, so your char
is converted to int
, and because it is signed, 0x99
as a char
is a negative quantity, so it gets sign-extended to 0xFFFFFF99
, and hence gets printed like that.
To get the result you expect, use one of:
printf("%02x", (unsigned char)a);
printf("%02x", a & 0xFF);
If your goal is to print hex value, you need to declare variable as uint8_t That is basically a byte and just print it as below
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint8_t a=0x99;
printf("%x",a);
}
Read below for integer promotion.
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
In your case applies rule 3, becouse printf expect unsigned int and you give signed char.