简体   繁体   English

VStudio C ++联合中的位域对齐

[英]VStudio c++ alignment of bitfield in union

In VStudio 2010, I'm trying to create a union to access a 2-byte value conveniently: 在VStudio 2010中,我试图创建一个联合以方便地访问2字节值:

#pragma pack(push,1) // disable padding
typedef struct {
    uint8_t r:3;
    uint8_t g:3;
    uint8_t b:3;
}tsRgb;

typedef union {
    uint16_t raw;
    tsRgb rgb; 
}tPixelData;
#pragma pack(pop)

int main(){
    tPixelData pixel;
    pixel.raw = 0xABE5;
    return 0;
}

I'm expecting to see pixel.r = 5, pixel.g = 4, pixel.b = 7. the r and g are ok, but the b is 3. 我期望看到p​​ixel.r = 5,pixel.g = 4,pixel.b =7。r和g都可以,但是b是3。

What am I doing wrong? 我究竟做错了什么? I assume I'm not alligning the bits correctly? 我认为我没有正确分配位?

The third field will be in a separate byte. 第三个字段将在一个单独的字节中。

In VC++ the bitfields do not cross the boundaries of the underlying type. 在VC ++中,位域不会跨越基础类型的边界。 When you have used 3+3 bits there are only 2 left, so the next field will use 3 bits from a fresh byte. 使用3 + 3位后,仅剩2位,因此下一个字段将使用新字节中的3位。

It might work better if you use uint16_t instead of uint8_t . 如果使用uint16_t而不是uint8_t可能会更好。

"Disable padding" works on the byte level, not on the bit level. “禁用填充”在字节级别上起作用,而不在位级别上起作用。

Using bit-fields is as you want to is fundamentally problematic. 想要使用位域从根本上来说是有问题的。 Per the C Standard , 6.7.2.1 Structure and union specifiers , paragraph 11 (since your question is also tagged C): 根据C标准 6.7.2.1结构和联合说明符第11段(因为您的问题也被标记为C):

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. 未指定可寻址存储单元的对齐方式。

The layout and alignment of the bits in a bit-field are all implementation-defined. 位域中位的布局和对齐方式均由实现定义。 Fields may or may not cross storage unit boundaries, they may be stored in any order. 字段可以跨也可以不跨存储单元边界,可以以任何顺序存储。

They're not portable at all. 它们根本不是便携式的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM