问题
I know that when using %x with printf() we are printing 4 bytes (an int in hexadecimal) from the stack. But I would like to print only 1 byte. Is there a way to do this ?
回答1:
Assumption:You want to print the value of a variable of 1 byte width, i.e., char.
In case you have a char variable say, char x = 0; and want to print the value, use %hhx format specifier with printf().
Something like
printf("%hhx", x);
Otherwise, due to default argument promotion, a statement like
printf("%x", x);
would also be correct, as printf() will not read the sizeof(unsigned int) from stack, the value of x will be read based on it's type and the it will be promoted to the required type, anyway.
回答2:
You need to be careful how you do this to avoid any undefined behaviour.
The C standard allows you to cast the int to an unsigned char then print the byte you want using pointer arithmetic:
int main()
{
int foo = 2;
unsigned char* p = (unsigned char*)&foo;
printf("%x", p[0]); // outputs the first byte of `foo`
printf("%x", p[1]); // outputs the second byte of `foo`
}
Note that p[0] and p[1] are converted to the wider type (the int), prior to displaying the output.
回答3:
You can use the following solution to print one byte with printf:
unsigned char c = 255;
printf("Unsigned char: %hhu\n", c);
回答4:
If you want to print a single byte that is present in a larger value type, you can mask and/or shift out the required value (e.g. int x = 0x12345678; x & 0x00FF0000 >> 16). Or just retrieve the required byte by casting the needed byte location using a (unsigned) char pointer and using an offset.
来源:https://stackoverflow.com/questions/41638330/how-to-print-1-byte-with-printf