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

查看 48|回复 4
作者:zhanglintc   
有这样一段 C 代码,就是往文件里写入一个 int 型的 1:
#include [u]
#include
#include
#include
#include
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);
}
文件生成后,分别hexdump和hexdump -C查看,显示的顺序有点不一样:
➜ [email protected]#2 ~ cat test.pid | hexdump -C
00000000  01 00 00 00                                       |....|
00000004
➜ [email protected]#2 ~ cat test.pid | hexdump   
0000000 0001 0000                              
0000004
一个是 0100 ,一个是 0001 。为啥呢?
看起来 hexdump -C 才是文件的实际存储顺序。

hexdump, int, include, pid

Eiden   
大小端区别 https://zh.wikipedia.org/wiki/%E5%AD%97%E8%8A%82%E5%BA%8F
adoal   
你以为是“0100”和“0001”,再仔细看看,其实是“01 then 00”(以字节( 8 位整数)为单位,两个独立的字节,显示时 8bit 一组,每 8bit 间空格隔开)和“whole 0001”(短字,以 16 位整数为单位,把两个相邻字节看作一个短字,显示时 16bit 一组,每 16bit 间空格隔开)。如#1 所说,多字节整数的存储有大小端区别,在 X86 上用的是小端序,所以内存里的 01 then 00 的值就是 0001 。
zhanglintc
OP
  
@Eiden @adoal 嗯嗯,大小端这个我知道了。
但我的主要在意的是,是不是可以认为 hexdump 输出的是这个短字的逻辑顺序 00 01 。
而 hexdump -C 输出的是这个短字的物理顺序 01 00 。
man hexdump 也没有看出来明确说这个问题 。
adoal   
@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 ,这两个有什么区别很明显的吧。
没有什么“逻辑顺序”、“物理顺序”,只有按不同的数据类型大小来解释。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部