首页 > 解决方案 > 如何将 32 位无符号整数分配给包含 32 位的位域

问题描述

我正在尝试创建一个总共有 32 位的位域结构,但是当我尝试为其分配一个 32 位数字时,我收到此错误:

从“无符号整数”到位字段的隐式截断将值从 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

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

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

#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
}

标签: c++bit-fields

解决方案


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

Color32 BLACK = {0xFF, 0x00, 0x00, 0x00};

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

struct Color32 {
    uint8_t a;
    uint8_t r;
    uint8_t g;
    uint8_t b;
};

推荐阅读