作为字符串的十六进制值 C

Hexadecimal values as Strings C

我正在为我的大学写一篇论文,运行 陷入了一些困惑。

int main(void) {
unsigned int i = 0x00646c72;
printf("H%x Wo%s\n", 57616, (char *) &i);
}

基本上在小端架构中打印出来:He110 World

如果这段代码由 Big Endian 架构执行,我必须告诉它会打印什么。

到目前为止我所知道的:

'H'、space、'W' 和 'o' 将保留在原处,因为它们是 8 位表示形式的字符串文字。

16进制的值57616是e110。据我所知,这应该以 little endian 存储为 10e1,但它仍然打印为 'e110',也许这与 %x 格式化程序的工作方式有关?

0x00646c72 转换为 ASCII 为 'dlr',因此在小端中它读取 'rld' 但在大端中它会打印 'dlr'。这个假设是否正确?

最后在一个非常相关的问题中:

#define VGABUF ((void *) 0xb8000)

void begin(void) {
    int *vga = VGABUF;
    *vga = 0x2f4b2f4f;

    while (1)
        continue;
}

我被要求修改此代码(显示绿色背景的 OK 标志)以在 Big Endian 架构中表现完全相同。 我想我应该将 vga 写成字符串文字,但是当我尝试它时,它没有打印任何东西。

The value 57616 in base 16 is e110. This in my knowledge should be stored in little endian as 10e1, but still it's printed as 'e110', maybe it has to do with how the %x formatter works?

正确,它的打印方式与字节顺序无关,这在大端机器上不会改变。

0x00646c72 translates to ASCII as 'dlr' so in little endian it reads 'rld' but in Big Endian it would print 'dlr'. Are this asumptions correct?

你忘记了开头的0x00。强制转换为 (char *) 这是 "rld" + 终止 0。 如果你有big endian,你会得到0、0x64、0x6c、0x72,终止的0将是第一个字符,打印的字符串将为空

所以结果会是 "he110 wo\n"