问题描述
我有一个与结构位字段有关的问题,请参阅下面的内容,因为我对应该使用哪个关键字来最好地描述我的问题一无所知:
I have a question related to structure bit fields, please see below as I am a bit clueless on which keywords I should use to best describe my issue:
上下文:我正在为MIPS R3000A汇编指令编写反汇编程序,该指令在2000年初用于Playstation程序.
Context: I am writing a disassembler for MIPS R3000A Assembly Instructions, the one that were used for Playstation Programs in the early 2000.
问题:我想知道是否在此代码中:
Issue: I would like to know if in this code:
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位字段中)
it is guaranteed that all compilers, using little endianness, will always using the op:6 bit-fields to store the first 6 MSB ? (which is a bit counter intuitive, you would assume that the last 6 bits are stored in the op bit field)
它是以下代码的替代方法:
It is an alternative to the following code:
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".
It is working fine on my side and it seems slightly faster using the structure approach, not to mention that is is more intuitive and clear, but I am afraid that it would not be guaranteed that the 6 first bits are stored in the second bit-field "op" of the structure.
推荐答案
C标准不保证位域的排列方式.它确实需要每个实现来定义它,因此它应该在编译器的文档中.Per C 2018 6.7.2.1 11:
The C standard does not guarantee how bit-fields are arranged. It does require each implementation to define it, so it should be in the documentation for a compiler. Per C 2018 6.7.2.1 11:
这篇关于结构中的位是否得到保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!