简体   繁体   English

将数组与整数打印为十六进制

[英]Printing array vs. integer as hex

I am using an API that uses a struct to represent an array (and allows filling up that array while accessing the struct). 我正在使用使用结构表示数组的API(并允许在访问结构时填充该数组)。

If data is a struct object, and direction is a uint32_t, run the following: 如果data是struct对象,而direction是uint32_t,请运行以下命令:

printf("0x%08X", data->magic);

I get the value: 0xAAAABEEF 我得到的值:0xAAAABEEF

while printing the array directly as such: 同时直接打印数组:

printf("0x");
for (int i = 0; i < size; ++i) {
  printf("%02X", payload[i]);
}

I get the value: 0xEFBEAAAA 我得到的值:0xEFBEAAAA

the struct definition goes like this: 结构定义如下:

struct Data {
  uint32_t magic;
} __attribute__((packed));

I believe the data variable is declared something like this: 我相信数据变量声明如下:

// Declared and initialized somewhat like this:
uint8_t payload[kMaxSize];
Data* data = reinterpret_cast<Data*>(payload);
data->magic = 0xAAAABEEF;

I am curious why the printf does not return the same value. 我很好奇为什么printf不返回相同的值。 Is it because the machine is storing the data as LSB (least significant byte)? 是否因为机器将数据存储为LSB(最低有效字节)?

Your guess is correct. 你的猜测是正确的。 In a little-endian processor (eg: x86 ), the least significant byte is stored first in memory. 低字节序处理器 (例如x86 )中,最低有效字节首先存储在内存中。 So the number 0xAAAABEEF will be stored as four bytes in memory: {0xEF, 0xBE, 0xAA, 0xAA} 因此,数字0xAAAABEEF将作为四个字节存储在内存中: {0xEF, 0xBE, 0xAA, 0xAA}

When your program looks at those four bytes in memory, the way the data is interpreted - its type - determines how it looks. 当程序查看内存中的这四个字节时,数据的解释方式(其类型 )将决定其外观。 If {0xEF, 0xBE, 0xAA, 0xAA} is interpreted as individual bytes, you get "EF BE AA AA". 如果将{0xEF, 0xBE, 0xAA, 0xAA}解释为单个字节,则会得到“ EF BE AA AA”。 But if it's interpreted as a uint32_t , then the computer knows to reverse the order and display it as "0xAAAABEEF". 但是,如果将其解释为uint32_t ,则计算机知道可以颠倒顺序并将其显示为“ 0xAAAABEEF”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM