[英]Why does printf not print out just one byte when printing hex?
pixel_data
is a vector
of char
. pixel_data
是char
的vector
。
When I do printf(" 0x%1x ", pixel_data[0] )
I'm expecting to see 0xf5
.当我执行
printf(" 0x%1x ", pixel_data[0] )
我期待看到0xf5
。
But I get 0xfffffff5
as though I was printing out a 4 byte integer instead of 1 byte.但是我得到
0xfffffff5
就好像我正在打印一个 4 字节的整数而不是 1 字节。
Why is this?为什么是这样? I have given
printf
a char
to print out - it's only 1 byte, so why is printf
printing 4?我给了
printf
一个要打印的char
——它只有 1 个字节,那么为什么printf
打印 4?
NB.注意。 the
printf
implementation is wrapped up inside a third party API but just wondering if this is a feature of standard printf
? printf
实现包含在第三方 API 中,但只是想知道这是否是标准printf
的功能?
You're probably getting a benign form of undefined behaviour because the %x
modifier expects an unsigned int
parameter and a char
will usually be promoted to an int
when passed to a varargs function.您可能会遇到未定义行为的良性形式,因为
%x
修饰符需要一个unsigned int
参数,而当传递给varargs函数时, char
通常会被提升为int
。
You should explicitly cast the char to an unsigned int
to get predictable results:您应该将 char 显式转换为
unsigned int
以获得可预测的结果:
printf(" 0x%1x ", (unsigned)pixel_data[0] );
Note that a field width of one is not very useful.请注意,字段宽度为 1 不是很有用。 It merely specifies the minimum number of digits to display and at least one digit will be needed in any case.
它仅指定要显示的最少位数,并且在任何情况下都至少需要一位。
If char
on your platform is signed then this conversion will convert negative char
values to large unsigned int
values (eg fffffff5
).如果您平台上的
char
是有符号的,那么此转换会将负char
值转换为大的unsigned int
值(例如fffffff5
)。 If you want to treat byte values as unsigned values and just zero extend when converting to unsigned int
you should use unsigned char
for pixel_data
, or cast via unsigned char
or use a masking operation after promotion.如果要将字节值视为无符号值,并且在转换为
unsigned int
时仅将零扩展为unsigned int
,则应将unsigned char
用于pixel_data
,或通过unsigned char
或在升级后使用屏蔽操作。
eg例如
printf(" 0x%x ", (unsigned)(unsigned char)pixel_data[0] );
or或者
printf(" 0x%x ", (unsigned)pixel_data[0] & 0xffU );
Better use the standard-format-flags更好地使用标准格式标志
printf(" %#1x ", pixel_data[0] );
then your compiler puts the hex-prefix for you.然后您的编译器为您放置十六进制前缀。
使用%hhx
printf("%#04hhx ", foo);
那么length
修饰符是最小长度。
Width-specifier in printf
is actually min-width. printf
宽度说明符实际上是最小宽度。 You can do printf(" 0x%2x ", pixel_data[0] & 0xff)
to print lowes byte (notice 2, to actually print two characters if pixel_data[0]
is eg 0xffffff02
).您可以执行
printf(" 0x%2x ", pixel_data[0] & 0xff)
来打印低字节(注意 2,如果pixel_data[0]
是例如0xffffff02
,则实际打印两个字符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.