本文介绍了如何用 printf 打印 1 个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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字节宽度的变量的值,即char.

如果您有一个 char 变量,例如 char x = 0; 并且想要打印该值,请使用 %hhx 格式说明符使用 printf().

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

类似的东西

 printf("%hhx", x);

否则,由于默认参数提升,像这样的语句

Otherwise, due to default argument promotion, a statement like

  printf("%x", x);

也是正确的,因为printf()不会从stack中读取sizeof(unsigned int)的值>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.

这篇关于如何用 printf 打印 1 个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:14