C 打印十六进制字节 [英] C print hex bytes

查看:90
本文介绍了C 打印十六进制字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C 程序中有代码,其中包含我想要迭代的十六进制数据,例如打印出每个十六进制字节:

I have code in a C program with hex data which I want to iterate over, for example to print out each of the hex bytes:

char input[] = "\x31\xd2\xb2\x30";
for (int i = 0; i < strlen(input); i++) {
    printf("%02X\n", input[i]);
}

然而,输出不是我所期望的,例如上面的打印:

However, the output is not what I expect, for example the above prints:

31
FFFFFFD2
FFFFFFB2
30

我也尝试将输出转换为 (unsigned int),但是我收到了相同的输出.

I also tried to cast the output as an (unsigned int), however I receive the same output.

有人能指出这个简单脚本的问题吗?

Can somebody point out the issue with this simple script?

推荐答案

传递给 printf 的参数是符号扩展的,除非您将它们强制转换为如下所示的无符号类型:

The arguments passed to printf are sign extended unless you cast them to an unsigned type like this:

printf("%02X\n", (unsigned char)input[i]);

这篇关于C 打印十六进制字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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