How to print 1 byte with printf?

旧巷老猫 提交于 2019-11-30 23:38:47

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.

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.

macario

You can use the following solution to print one byte with printf:

unsigned char c = 255;
printf("Unsigned char: %hhu\n", c);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!