结构中的位是否有保证
Are bits in the structure guaranteed
我有一个与结构位字段相关的问题,请看下面,因为我对应该使用哪些关键字来最好地描述我的问题有点无能为力:
上下文:我正在为 MIPS R3000A 汇编指令编写反汇编程序,该指令在 2000 年初用于 Playstation 程序。
问题:我想知道是否在这段代码中:
struct Instruction {
u32 other:26;
u32 op:6;
};
//main:
Instruction instruction = *(Instruction*)(data + pc);
printf("%02x\n", instruction.op);
保证所有使用小字节序的编译器将始终使用 op:6 位字段来存储前 6 个 MSB? (这有点违反直觉,你会假设最后 6 位存储在 op 位字段中)
它是以下代码的替代:
static uint32_t get_op_code(uint32_t data) {
uint16_t mask = (1 << 6) - 1;
return (data >> 26) & mask;
}
//main:
uint32_t instruction = *(uint32_t*)(data + pc);
uint32_t op = get_op_code(instruction);
printf("%02x\n", op);
在我这边工作正常,使用结构方法似乎稍微快一些,而且更直观和清晰,但我担心不能保证存储前 6 位在结构的第二个位域 "op" 中。
C 标准不保证位域的排列方式。它确实需要每个实现来定义它,所以它应该在编译器的文档中。根据 C 2018 6.7.2.1 11:
An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
我有一个与结构位字段相关的问题,请看下面,因为我对应该使用哪些关键字来最好地描述我的问题有点无能为力:
上下文:我正在为 MIPS R3000A 汇编指令编写反汇编程序,该指令在 2000 年初用于 Playstation 程序。
问题:我想知道是否在这段代码中:
struct Instruction {
u32 other:26;
u32 op:6;
};
//main:
Instruction instruction = *(Instruction*)(data + pc);
printf("%02x\n", instruction.op);
保证所有使用小字节序的编译器将始终使用 op:6 位字段来存储前 6 个 MSB? (这有点违反直觉,你会假设最后 6 位存储在 op 位字段中)
它是以下代码的替代:
static uint32_t get_op_code(uint32_t data) {
uint16_t mask = (1 << 6) - 1;
return (data >> 26) & mask;
}
//main:
uint32_t instruction = *(uint32_t*)(data + pc);
uint32_t op = get_op_code(instruction);
printf("%02x\n", op);
在我这边工作正常,使用结构方法似乎稍微快一些,而且更直观和清晰,但我担心不能保证存储前 6 位在结构的第二个位域 "op" 中。
C 标准不保证位域的排列方式。它确实需要每个实现来定义它,所以它应该在编译器的文档中。根据 C 2018 6.7.2.1 11:
An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.