这段代码中关于 n 在 pc[i] 中的表示是怎么回事
What's going on in this snippet regarding the representation of n in pc[i]
我不知道发生了什么。而不是 uint8_t,我猜想我们需要强制转换为 1 字节类型的指针(如 char 或 bool)才能实现此行为。我想相反的性质是由于字节顺序?
编辑:我发现我的思维错误,当然 uint8_t 的大小是 8 位 = 1 字节,就像 bool 和 char(至少在我的机器上是这样)。我错误地想到了 sizeof(pc),它是一个指针,因此在我的 64 位机器上是 8byte。现在一切都对字节顺序有意义了。
谢谢,感谢您的帮助
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::hex;
int main()
{
int n{0x12345678};
cout << "01| n=0x" << hex << n << endl;
uint8_t* pc{(uint8_t*)&n};
cout << "02| n[0]=0x" << hex << +pc[0]
<< ", n[1]=0x" << +pc[1] // small trick: + to var to use as number
<< ", n[2]=0x" << +pc[2]
<< ", n[3]=0x" << +pc[3] << endl;
pc[1]=0xab;
pc[2]=0xcd;
cout << "03| n[0]=0x" << hex << +pc[0]
<< ", n[1]=0x" << +pc[1]
<< ", n[2]=0x" << +pc[2]
<< ", n[3]=0x" << +pc[3] << endl;
return 0;
}
输出:
01| n=0x12345678
02| n[0]=0x78, n[1]=0x56, n[2]=0x34, n[3]=0x12
03| n[0]=0x78, n[1]=0xab, n[2]=0xcd, n[3]=0x12
问题的根源在于字节顺序:多字节数字中的字节顺序。
小字节序:
最低有效字节在前。
给定 0x12345678,该值将存储在 Little Endian 中:
0x78 0x56 0x34 0x12
大字节序:
最高有效字节在前。
给定 0x12345678,该值将存储在 Big Endian 中:
0x12 0x34 0x56 0x78
字节顺序是处理器级别的定义。不同的处理器以不同的方法存储多字节数字。
我不知道发生了什么。而不是 uint8_t,我猜想我们需要强制转换为 1 字节类型的指针(如 char 或 bool)才能实现此行为。我想相反的性质是由于字节顺序?
编辑:我发现我的思维错误,当然 uint8_t 的大小是 8 位 = 1 字节,就像 bool 和 char(至少在我的机器上是这样)。我错误地想到了 sizeof(pc),它是一个指针,因此在我的 64 位机器上是 8byte。现在一切都对字节顺序有意义了。
谢谢,感谢您的帮助
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::hex;
int main()
{
int n{0x12345678};
cout << "01| n=0x" << hex << n << endl;
uint8_t* pc{(uint8_t*)&n};
cout << "02| n[0]=0x" << hex << +pc[0]
<< ", n[1]=0x" << +pc[1] // small trick: + to var to use as number
<< ", n[2]=0x" << +pc[2]
<< ", n[3]=0x" << +pc[3] << endl;
pc[1]=0xab;
pc[2]=0xcd;
cout << "03| n[0]=0x" << hex << +pc[0]
<< ", n[1]=0x" << +pc[1]
<< ", n[2]=0x" << +pc[2]
<< ", n[3]=0x" << +pc[3] << endl;
return 0;
}
输出:
01| n=0x12345678
02| n[0]=0x78, n[1]=0x56, n[2]=0x34, n[3]=0x12
03| n[0]=0x78, n[1]=0xab, n[2]=0xcd, n[3]=0x12
问题的根源在于字节顺序:多字节数字中的字节顺序。
小字节序:
最低有效字节在前。
给定 0x12345678,该值将存储在 Little Endian 中:
0x78 0x56 0x34 0x12
大字节序:
最高有效字节在前。 给定 0x12345678,该值将存储在 Big Endian 中:
0x12 0x34 0x56 0x78
字节顺序是处理器级别的定义。不同的处理器以不同的方法存储多字节数字。