打印十六进制再一个字符数组的presentation [] [英] Printing the hexadecimal representation of a char array[]

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

问题描述

我有8个字节数组,我试图打印出16进制表示。使用的printf(%X,数组)我可以在第一个字节得到并打印出来,但我发现0xffffff9b或诸如此类的东西。有没有办法让没有F的?

I've got an array of 8 bytes that I'm trying to print out the hexadecimal notation for. Using printf("%x", array) I can get at the first byte and print it out but I'm getting "0xffffff9b" or something of the sort. Is there a way to get the notation without the "f's"?

我想打印出每个元素看起来像:

I would like to print out each element looking something like:

为0x9A 0x43中,0X0D

推荐答案

printf("%x", array);

将最有可能在打印十六进制阵列的第一个元素的地址的。我说:最有可能,是因为试图就好像它是一个来打印地址的行为unsigned int类型是不确定的。如果你真的想打印的地址,做正确的方式,它是:

will most likely print the address of the first element of your array in hexadecimal. I say "most likely" because the behavior of attempting to print an address as if it were an unsigned int is undefined. If you really wanted to print the address, the right way to do it would be:

printf("%p", (void*)array);

(数组前pression,在大多数情况下,隐式转换(衰变)一个指向数组的第一个元素。)

(An array expression, in most contexts, is implicitly converted to ("decays" to) a pointer to the array's first element.)

如果你要打印数组的每个元素,你就必须这样做明确。在%S格式需要一个指针为字符串的第一个字符,并告诉的printf 来遍历字符串,打印每个字符。没有格式,做那种十六进制的东西,所以你必须自己做。

If you want to print each element of your array, you'll have to do so explicitly. The "%s" format takes a pointer to the first character of a string and tells printf to iterate over the string, printing each character. There is no format that does that kind of thing in hexadecimal, so you'll have to do it yourself.

例如,给出:

unsigned char arr[8];

您可以打印单元5是这样的:

you can print element 5 like this:

printf("0x%x", arr[5]);

或者,如果你想要一个前导零:

or, if you want a leading zero:

printf("0x%02x", arr[5]);

%X格式需要一个 unsigned int类型参数和符号你传递字符值隐含的推荐 unsigned int类型,所以这是类型正确的。您可以使用%X打印十六进制数字 A ˚F小写,%X为大写(您同时使用在你的例子)。

The "%x" format requires an unsigned int argument, and the unsigned char value you're passing is implicitly promoted to unsigned int, so this is type-correct. You can use "%x" to print the hex digits a throughf in lower case, "%X" for upper case (you used both in your example).

(请注意,为0x%02X格式效果最好,如果字节是8位;这是没有保证的,但它几乎肯定你的任何系统的情况下,可能使用。)

(Note that the "0x%02x" format works best if bytes are 8 bits; that's not guaranteed, but it's almost certainly the case on any system you're likely to use.)

我将让你写适当的循环,并决定如何划定输出。

I'll leave it to you to write the appropriate loop and decide how to delimit the output.

这篇关于打印十六进制再一个字符数组的presentation []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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