hexdump 和 hexdump -C 有什么区别,为啥输出的顺序不一样

324 天前
 zhanglintc

有这样一段 C 代码,就是往文件里写入一个 int 型的 1:

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int main() {
    const char *path = "test.pid";
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    int v = 1;
    if (fd > 0){
        write(fd, &v, sizeof(int));
    } else {
        int error_code = errno;
        const char* error_message = strerror(error_code);
        printf("Failed to open file, reason: %s\n", error_message);
    }
    close(fd);
}

文件生成后,分别hexdumphexdump -C查看,显示的顺序有点不一样:

➜ lane@vbox#2 ~ cat test.pid | hexdump -C
00000000  01 00 00 00                                       |....|
00000004

➜ lane@vbox#2 ~ cat test.pid | hexdump   
0000000 0001 0000                              
0000004

一个是 0100 ,一个是 0001 。为啥呢? 看起来 hexdump -C 才是文件的实际存储顺序。

745 次点击
所在节点    问与答
7 条回复
Eiden
324 天前
adoal
324 天前
你以为是“0100”和“0001”,再仔细看看,其实是“01 then 00”(以字节( 8 位整数)为单位,两个独立的字节,显示时 8bit 一组,每 8bit 间空格隔开)和“whole 0001”(短字,以 16 位整数为单位,把两个相邻字节看作一个短字,显示时 16bit 一组,每 16bit 间空格隔开)。如#1 所说,多字节整数的存储有大小端区别,在 X86 上用的是小端序,所以内存里的 01 then 00 的值就是 0001 。
zhanglintc
324 天前
@Eiden @adoal 嗯嗯,大小端这个我知道了。

但我的主要在意的是,是不是可以认为 hexdump 输出的是这个短字的逻辑顺序 00 01 。
而 hexdump -C 输出的是这个短字的物理顺序 01 00 。

man hexdump 也没有看出来明确说这个问题 。
adoal
324 天前
@zhanglintc 我已经说了,第一个是 01 then 00 ,第二个是 whole 0001 ,有空格和没空格,显示的都不一样的。你先想明白 multiple-byte integer 和 multiple bytes 的区别就明白了。

你说你看了 man hexdump ,再仔细看看?不加格式参数时按 -x 来( If no format strings are specified, the default display is very similar to the -x output format ),-x 是--two-bytes-hex ,-C 是 Canonical hex+ASCII display ,这两个有什么区别很明显的吧。

没有什么“逻辑顺序”、“物理顺序”,只有按不同的数据类型大小来解释。
zhanglintc
324 天前
@adoal 啊,OKOK ,这回明白了。加不加空格是两种显示方法。那我懂了。
buffzty
324 天前
你完全没必要问人,把 1 改成 0x12345678 答案就出来了
简单的问题问人容易使自己退步
zhanglintc
324 天前
@buffzty 脑子里那个弯儿没转过来之前改成这个也看不出来

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/949858

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX