C/C ++以十六进制打印字节,获取奇怪的十六进制值 [英] C/C++ Printing bytes in hex, getting weird hex values

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

问题描述

我正在使用以下命令以十六进制的形式打印出数字:

I am using the following to print out numbers from an array in hex:

char buff[1000];

// Populate array....

int i;
for(i = 0; i < 1000; ++i)
{
    printf("[%d] %02x\n", i,buff[i]);
}

但是我有时会打印出奇怪的值:

but I sometimes print weird values:

byte[280] 00     
byte[281] 00     
byte[282] 0a     
byte[283] fffffff4         // Why is this a different length?
byte[284] 4e      
byte[285] 66      
byte[286] 0a   

为什么会打印'fffffff4'?

Why does this print 'fffffff4'?

推荐答案

使用%02hhx 作为格式字符串.

CppReference 中,%02x 接受 unsigned int .当您将参数传递给 printf()时,这是 variadic函数 buff [i] 会自动转换为 int .然后格式说明符%02x 使 printf()将该值解释为 int ,因此潜在的负值如(char)-1被解释并打印为(int)-1 ,这就是您观察到的原因.

From CppReference, %02x accepts unsigned int. When you pass the arguments to printf(), which is a variadic function, buff[i] is automatically converted to int. Then the format specifier %02x makes printf() interprets the value as int, so potential negative values like (char)-1 get interpreted and printed as (int)-1, which is the cause of what you observed.

还可以推断出您的平台已签名 char 类型和32位 int 类型.

It can also be inferred that your platform has signed char type, and a 32-bit int type.

长度修饰符 hh 将告诉 printf()解释为 char 类型提供的任何内容,因此%hhx unsigned char 的正确格式说明符.

The length modifier hh will tell printf() to interpret whatever supplied as char type, so %hhx is the correct format specifier for unsigned char.

或者,您可以在打印之前将数据转换为 unsigned char .喜欢

Alternatively, you can cast the data to unsigned char before printing. Like

printf("[%d] %02x\n", i, (unsigned char)buff[i]);

这还可以防止出现负值,因为 int 可以(几乎)始终包含 unsigned char 值.

This can also prevent negative values from showing up as too long, as int can (almost) always contain unsigned char value.

请参见以下示例:

#include <stdio.h>

int main(){
    signed char a = +1, b = -1;
    printf("%02x %02x %02hhx %02hhx\n", a, b, a, b);
    return 0;
}

以上程序的输出为:

01 ffffffff 01 ff

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

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