c++ - 如何将 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
}
解决方案
您可以在此处使用聚合初始化
Color32 BLACK = {0xFF, 0x00, 0x00, 0x00};
顺便说一句,我建议将您的Color32
结构修改为以下内容,这与指定成员的位字段具有相同的效果
struct Color32 {
uint8_t a;
uint8_t r;
uint8_t g;
uint8_t b;
};
推荐阅读
- android - 如何按顺序运行android仪器测试?
- dialogflow-es - Dialogflow Fulfillment LINE 自定义负载
- django - 如何验证 Django 模型是否具有通过 GET 参数给出的字段?
- java - Update the JSON element to NULL if it has a specific value in it
- azure - Azure WebApp + SignalR + .net core + blazor (StatusCode: 405 'Method Not Allowed')
- mysql - 如何使用 json 在 Spring Boot 中为单个属性添加数据库中特定键的多个值
- google-cloud-platform - 为什么 GCP 负载均衡器打开端口 5432、5900、5901?
- go - 使用 Golang 的 Google Cloud Functions 工作流
- windows - 无法在 docker 容器中安装 VI 编辑器/vim
- redis - Is Redis security weak but does not matter?