结构中的位是否得到保证 [英] Are bits in the structure guaranteed

查看:57
本文介绍了结构中的位是否得到保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与结构位字段有关的问题,请参阅下面的内容,因为我对应该使用哪个关键字来最好地描述我的问题一无所知:

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:

实现可以分配任何足够大的可寻址存储单元来容纳位字段.如果有足够的空间,应将紧随结构中另一个位域之后的位域打包到同一单元的相邻位中.如果剩余空间不足,则将实现不当的位字段放入下一个单元还是与相邻单元重叠.单位内位域的分配顺序(从高位到低位或从低位到高位)是实现定义的.未指定可寻址存储单元的对齐方式.

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.

这篇关于结构中的位是否得到保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆