如何为包含32位的位字段分配32位无符号整数

Kyl*_*ner -2 c++ bit-fields

我试图创建一个具有32位总位数的位域结构,但是当我尝试为其分配32位数字时,出现此错误:

从'unsigned int'到位字段的隐式截断将值从4278190080更改为0

这是我的结构以及如何使用它

struct Color32 {
    uint32_t a : 8;
    uint32_t r : 8;
    uint32_t g : 8;
    uint32_t b : 8;
};


Color32 BLACK = {0xFF000000}; // this line has the compilation error
Run Code Online (Sandbox Code Playgroud)

我看到了有关位字段分配的其他问题,但它们似乎都使用按位运算来设置各个字段。

还有一个具有以下示例的参考,似乎与我使用它的方式相同,只有我自己不会编译:

#include <iostream>
struct S {
 // three-bit unsigned field,
 // allowed values are 0...7
 unsigned int b : 3;
};
int main()
{
    S s = {6};
    ++s.b; // store the value 7 in the bit field
    std::cout << s.b << '\n';
    ++s.b; // the value 8 does not fit in this bit field
    std::cout << s.b << '\n'; // formally implementation-defined, typically 0
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 6

您可以在此处使用聚合初始化

Color32 BLACK = {0xFF, 0x00, 0x00, 0x00};
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我建议将您的Color32结构修改为以下内容,这与指定成员的bit字段具有相同的效果

struct Color32 {
    uint8_t a;
    uint8_t r;
    uint8_t g;
    uint8_t b;
};
Run Code Online (Sandbox Code Playgroud)


tte*_*ple 5

像这样的事情会给你两全其美的:

    struct Color32 {
    union {
        uint32_t color;
        struct {
            uint32_t b : 8;
            uint32_t g : 8;
            uint32_t r : 8;
            uint32_t a : 8;
        };
    };
};

// will construct using single value
Color32 test{ 0x01020304 };
Color32 black{0xff000000 };

// can assign to individual fields
test.a = 0x04;
test.r = 0x03;
test.g = 0x02;
test.b = 0x01;

// can assign to the whole value like this.
test.color = 0xff000000;
test.color = black.color;
Run Code Online (Sandbox Code Playgroud)

一个问题是结构中 a、b、g、r 的顺序可能取决于您的特定编译器。对于 VS2017 编译到 windows 目标,显示的顺序将产生预期的结果。我相信可能有办法以某种方式强制命令,但我不熟悉如何去做。