ahg*_*k78 5 c printf format-specifiers
我知道在使用%x时printf()我们int从堆栈中打印4个字节(十六进制).但我想只打印1个字节.有没有办法做到这一点 ?
Sou*_*osh 11
假设:您想要打印1个字节宽度的变量值,即char.
如果你有一个char变量说,char x = 0;并想要打印该值,请使用%hhx格式说明符printf().
就像是
printf("%hhx", x);
Run Code Online (Sandbox Code Playgroud)
否则,由于默认参数提升,声明就像
printf("%x", x);
Run Code Online (Sandbox Code Playgroud)
也是正确的,因为printf()不会sizeof(unsigned int)从堆栈读取,x将根据它的类型读取值,无论如何它将被提升为所需的类型.
您需要注意如何执行此操作以避免任何未定义的行为。
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`
}
Run Code Online (Sandbox Code Playgroud)
请注意,在显示输出之前,p[0]和p[1]被转换为更宽的类型 (the int)。
小智 5
您可以使用以下解决方案打印一个字节printf:
unsigned char c = 255;
printf("Unsigned char: %hhu\n", c);
Run Code Online (Sandbox Code Playgroud)