C语言 如何用 printf 打印 1 个字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41638330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:34:20  来源:igfitidea点击:

How to print 1 byte with printf?

cprintfformat-specifiers

提问by ahg8tOPk78

I know that when using %xwith printf()we are printing 4 bytes (an intin hexadecimal) from the stack. But I would like to print only 1 byte. Is there a way to do this ?

我知道当使用%xwith时,printf()我们int从堆栈中打印 4 个字节(十六进制)。但我只想打印 1 个字节。有没有办法做到这一点 ?

回答by Sourav Ghosh

Assumption:You want to print the value of a variable of 1 byte width, i.e., char.

假设:您要打印一个 1 字节宽度的变量的值,即char.

In case you have a charvariable say, char x = 0;and want to print the value, use %hhxformat specifier with printf().

如果您有一个char变量 say,char x = 0;并且想要打印该值,请使用%hhx带有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 xwill be read based on it's type and the it will be promoted to the required type, anyway.

也是正确的,因为printf()不会sizeof(unsigned int)stack读取, 的值x将根据它的类型读取,并且无论如何它将被提升为所需的类型。

回答by Bathsheba

You need to be careful how you do this to avoid any undefined behaviour.

您需要注意如何执行此操作以避免任何未定义的行为

The C standard allows you to cast the intto an unsigned charthen print the byte you want using pointer arithmetic:

C 标准允许您将int转换为 ,unsigned char然后使用指针算法打印您想要的字节:

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.

请注意,在显示输出之前,p[0]p[1]被转换为更宽的类型 (the int)。

回答by macario

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

您可以使用以下解决方案打印一个字节printf

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

回答by Ton Plooij

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.

如果您想打印存在于较大值类型中的单个字节,您可以屏蔽和/或移出所需的值(例如 int x = 0x12345678; x & 0x00FF0000 >> 16)。或者只是通过使用(无符号)字符指针和偏移量转换所需的字节位置来检索所需的字节。