Problem: A character type in 16 output, the output format is 0xAB, 0x is required after 2 bits, not enough 2 bit 0, such as "0x0b".
Common error practices are:
- #include <stdio.h>
- int Main ()
- {
- char a = 0x41; //A = ' a '
- printf ( "The hex value of a is 0x%02x\n", a);
- return 0;
- }
If a = 0xf1, the above output will be 0xfffffff1 instead of 0XF1.
The reason forthis is that%x is unsigned int or int output , so printf ("%x", a) will automatically raise the a type when executed (char will be promoted to int;
Unsigned char will be promoted to unsigned int), note that Char is signed (signed),
If A is negative at this point, it will be 1 in front of the promotion, i.e. 0xf1 = 0xfffffff1 in the inverse example, and unsigned char It only makes up 0 when it's lifted.
Workaround 1. Forcing type conversions
- #include <stdio.h>
- int Main ()
- {
- char a = 0xf1;
- printf ( "The hex value of a is 0x%02x\n", (unsigned char) a);
- return 0;
- }
Method 2. Precise printing format
- #include <stdio.h>
- int Main ()
- {
- char a = 0xf1;
- printf ( "The hex value of a is 0x%02hhx\n", a);
- return 0;
- }
HH will convert int to char;unsigned int into unsigned char. Specifically you can see the details in Man 3 printf.
Shell Code
- HH A Following integer conversion corresponds to A signed char or unsigned char argument,
- or a following n conversion corresponds to a pointer to a signed char argument.
Method 3. The number of forced bits is 1 byte
- #include <stdio.h>
- int Main ()
- {
- char a = 0xf1;
- printf ( "The hex value of a is 0x%02x\n", (A&0xff));
- return 0;
- }
The implicit procedure above is to raise char a to int, and then to 0xFF.
0x%02x 16-Input output of the character type