
有这样一段 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); } 文件生成后,分别hexdump和hexdump -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 才是文件的实际存储顺序。
1 Eiden 2023 年 6 月 19 日 |
2 adoal 2023 年 6 月 19 日 你以为是“0100”和“0001”,再仔细看看,其实是“01 then 00”(以字节( 8 位整数)为单位,两个独立的字节,显示时 8bit 一组,每 8bit 间空格隔开)和“whole 0001”(短字,以 16 位整数为单位,把两个相邻字节看作一个短字,显示时 16bit 一组,每 16bit 间空格隔开)。如#1 所说,多字节整数的存储有大小端区别,在 X86 上用的是小端序,所以内存里的 01 then 00 的值就是 0001 。 |
3 zhanglintc OP |
4 adoal 2023 年 6 月 19 日 @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 ,这两个有什么区别很明显的吧。 没有什么“逻辑顺序”、“物理顺序”,只有按不同的数据类型大小来解释。 |
5 zhanglintc OP @adoal 啊,OKOK ,这回明白了。加不加空格是两种显示方法。那我懂了。 |
6 buffzty 2023 年 6 月 19 日 你完全没必要问人,把 1 改成 0x12345678 答案就出来了 简单的问题问人容易使自己退步 |
7 zhanglintc OP @buffzty 脑子里那个弯儿没转过来之前改成这个也看不出来 |