为什么十六进制打印什么时候的printf打印不出来只是一个字节? [英] Why does printf not print out just one byte when printing hex?

查看:125
本文介绍了为什么十六进制打印什么时候的printf打印不出来只是一个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pixel_data 字符矢量

当我这样做的printf(0X%1X,pixel_data [0])我期待看到 0xf5

不过,我得到 0xfffffff5 好像被打印出一个4字节的整数,而不是1个字节。

这是为什么?我已经给的printf A 字符打印出来 - 它只有1个字节,那么,为什么 printf的打印4?

NB。在的printf 实施包裹起来第三方API内,但只是想知道如果这是标准功能的printf <? / p>

解决方案

你可能会得到未定义行为的一种良性的形式,因为%X 修改预计的 unsigned int类型参数和字符通常会被提升到 INT 当传递到的可变参数的功能。

您应该显式转换字符到 unsigned int类型来获得predictable结果:

 的printf(0X%1X(无符号)pixel_data [0]);

请注意,一个的字段宽度的一个是不是非常有用。它仅仅指定的最小位数,以显示和至少一个数字将在任何情况下是必要的。

如果字符你的平台上已签名,则此转换将负字符值大 unsigned int类型值(例如 fffffff5 )。如果你要正确对待字节值都是无符号数,只是零扩展转换为 unsigned int类型时你应该使用 unsigned char型 pixel_data ,或通过 unsigned char型投或升级后使用屏蔽操作。

例如

 的printf(为0x%X(符号)(unsigned char型)pixel_data [0]);

 的printf(为0x%X(无符号)pixel_data [0]&安培; 0xffU);

pixel_data is a vector of char.

When I do printf(" 0x%1x ", pixel_data[0] ) I'm expecting to see 0xf5.

But I get 0xfffffff5 as though I was printing out a 4 byte integer instead of 1 byte.

Why is this? I have given printf a char to print out - it's only 1 byte, so why is printf printing 4?

NB. the printf implementation is wrapped up inside a third party API but just wondering if this is a feature of standard 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.

You should explicitly cast the char to an unsigned int to get predictable results:

printf(" 0x%1x ", (unsigned)pixel_data[0] );

Note that a field width of one is not very useful. 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 (e.g. 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.

e.g.

printf(" 0x%x ", (unsigned)(unsigned char)pixel_data[0] );

or

printf(" 0x%x ", (unsigned)pixel_data[0] & 0xffU );

这篇关于为什么十六进制打印什么时候的printf打印不出来只是一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆