I was studying how C stores data in memory by bit patterns.
However I have confronted some issues when it comes to printf
formatting.
I have saved
In this expression
(unsigned int) a
the integer promotions are applied to the object a
.
From the C Standard (6.3.1.1 Boolean, characters, and integers)
2 The following may be used in an expression wherever an int or unsigned int may be used:
— An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.
— A bit-field of type _Bool, int, signed int, or unsigned int.
If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. 58) All other types are unchanged by the integer promotions.
and
3 The integer promotions preserve value including sign. As discussed earlier, whether a ‘‘plain’’ char is treated as signed is implementation-defined.
If you want that in the result object after casting the character object woulf be represented as having the type unsigned char
then you have to write
(unsigned char) a
As the value of the promoted expression (unsigned char) a
can be represented in the type unsigned int then the second cast (to unsigned int) is not required. The C Standard allows to use arguments pf the type int instead of the type unsigned int if the value is represented in the both types. You could just write
printf("a : %x , b : %x\n" , (unsigned char) a, (unsigned int) b);