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 ?
- 133,132
- 16
- 183
- 261
- 317
- 1
- 2
- 8
-
1You ought to tag the language. Is this C? – Bathsheba Jan 13 '17 at 15:46
-
Your assumption is not correct. `printf("%x", x)` prints the value of `x` in hexadecimal form. The size of `x` is assumed to be of type `(int)`, but it's not necessarily 4 bytes. – giusti Jan 13 '17 at 15:46
-
I've added the C tag. I *think* my answer is correct, please downvote if it isn't. – Bathsheba Jan 13 '17 at 15:50
-
_only one byte_ can you elaborate? is it a `char` variable? or is it that you want to print only one byte of a larger variable? – Sourav Ghosh Jan 13 '17 at 16:16
-
Possible duplicate of [Printing hexadecimal characters in C](https://stackoverflow.com/questions/8060170/printing-hexadecimal-characters-in-c) – Ciro Santilli OurBigBook.com Nov 06 '18 at 19:45
4 Answers
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.
- 133,132
- 16
- 183
- 261
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.
- 231,907
- 34
- 361
- 483
-
1Nice. Suggest a separator though to not mash output together. Only corner problem is with rare `sizeof(int) == 1`. Maybe use `for (size_t i = 0; i< sizeof foo; i++) printf("%x\n", p[i]);` to print all bytes - even if there is only 1. – chux - Reinstate Monica Jan 13 '17 at 17:51
You can use the following solution to print one byte with printf:
unsigned char c = 255;
printf("Unsigned char: %hhu\n", c);
- 27,532
- 16
- 147
- 165
- 61
- 1
- 3
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.
- 2,583
- 12
- 15