c - 结构中的位是否有保证

标签 c structure mips endianness mips32

我有一个与结构位字段相关的问题,请看下面,因为我有点不知道应该使用哪些关键字来最好地描述我的问题:

上下文:我正在为 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.

关于c - 结构中的位是否有保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57307550/

相关文章:

c - 编译发布版本后,我的应用程序开始表现得很奇怪

c - 从 stdin 或 file 输入,C

c++ - 将结构的动态数组传递给 GPU 内核

mips - 如何在MIPS拱上获取当前的PC寄存器值?

c - 将 atexit 注册到嵌套函数会在 gcc 下返回段错误

c - 生成任意大小的字符串 append 其他字符串 : how?

c - 函数指针中标记之前的预期标识符

c - 数组类型的元素类型不完整,无法将结构数组传递给函数

assembly - .double 类型的变量是否存储在两个寄存器中?

algorithm - Mips 汇编程序中的快速排序