我想知道 int32_t 的位顺序如何存储在内存中,所以我编写了一些代码来打印。
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
void print_i8_as_bits(int8_t num) {
#pragma pack(1)
struct Byte {
unsigned bit_0: 1;
unsigned bit_1: 1;
unsigned bit_2: 1;
unsigned bit_3: 1;
unsigned bit_4: 1;
unsigned bit_5: 1;
unsigned bit_6: 1;
unsigned bit_7: 1;
};
#pragma pack()
assert(sizeof(struct Byte) == 1); // your compiler didn't not support #pragma pack(), try gcc
struct Byte *byte = (struct Byte*) #
printf(
"%u%u%u%u%u%u%u%u",
byte->bit_0,
byte->bit_1,
byte->bit_2,
byte->bit_3,
byte->bit_4,
byte->bit_5,
byte->bit_6,
byte->bit_7
);
}
void print_i32_as_bits(int32_t num) {
int8_t *bytes = (int8_t*) #
for(size_t i = 0; i < 4; ++i) {
print_i8_as_bits(bytes[i]);
printf(" ");
}
}
int main() {
int32_t num = 3;
print_i32_as_bits(num);
printf("\n");
return 0;
}
$ gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
$ gcc print_bitfields.c && ./a.out
11000000 00000000 00000000 00000000
$ file ./a.out
./a.out: ELF 64-bit LSB pie executable, x86-64,
version 1 (SYSV), dynamically linked,
interpreter /lib64/ld-linux-x86-64.so.2,
BuildID[sha1]=ec61c8110d755b9b9216325536bcd1bcdc36cf1b,
for GNU/Linux 3.2.0, not stripped
最初,我错误地期望输出为:00000011 00000000 00000000 00000000
但它是:11000000 00000000 00000000 00000000
所以我搜索并找到了这个:
使用 GCC,大端机器首先布置位大端,而小端机器首先布置位小端。
但是没有外部链接。
我可以假设 gcc 编译的 LSB 可执行文件同时暗示“最低有效字节”和“最低有效位”吗?
或者这只是 gcc 在 x86_64 计算机上的特定行为?
[注]:LSB = 最低有效字节在前 = 小尾数
首先打印最低有效位是没有意义的。这个公约是强大的并且具有深厚的文化根基。就像十进制数字 12345 意味着 5 是最低有效数字一样,对于这个数字是否也可以表示为 54321 没有争议或困惑。没有人这样做。