相同大小的int与BGRA并集会产生不同的结果
int vs. BGRA union of the same size produces different results
有人能解释一下下面三个函数之间的区别吗?
typedef union
{
std::uint8_t B, G, R, A;
std::uint32_t Colour;
} BGRA;
第一:
void Image::process_pixels(void* out, void* in)
{
unsigned int i, j;
BGRA* pOut = (BGRA*)out;
unsigned char* pIn = (unsigned char*)in;
for (i = 0; i < height; ++i)
{
for (j = 0; j < width; ++j)
{
pOut->B = *(pIn++);
pOut->G = *(pIn++);
pOut->R = *(pIn++);
pOut->A = *(pIn++);
++pOut;
}
}
}
第二:
void Image::process_pixels(void* out, void* in)
{
unsigned int i, j;
unsigned int* pOut = (unsigned int*)out;
unsigned int* pIn = (unsigned int*)in;
for (i = 0; i < height; ++i)
{
for (j = 0; j < width; ++j)
{
*pOut++ = *pIn++
}
}
}
第三:
void Image::process_pixels(void* out, void* in)
{
unsigned int i, j;
BGRA* pOut = (BGRA*)out;
unsigned char* pIn = (unsigned char*)in;
for (i = 0; i < height; ++i)
{
for (j = 0; j < width; ++j)
{
memcpy(pOut, pIn, sizeof(int));
++pOut;
pIn += sizeof(int);
}
}
}
如果我使用第二个或第三个实现,代码运行良好。图像渲染正确。但是,如果我使用第一个实现,则没有任何内容能够正确呈现。
我可以保证sizeof(BGRA) = sizeof(int)
。我可以保证像素的BGRA
格式。然而不知怎么的,我得到了不同的结果。。
我一辈子都看不到前两个实现和后两个实现之间的区别。有什么想法吗?
typedef union
{
std::uint8_t B, G, R, A;
std::uint32_t Colour;
} BGRA;
这里,B
、G
、R
和A
是共享相同地址的4个元素
您应该将B
、G
、R
和A
包含在类似的结构中
typedef union
{
struct {
std::uint8_t B, G, R, A;
} Components;
std::uint32_t Colour;
} BGRA;
这个联盟有五个成员。你似乎认为它只有两个。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何让C++'tally up'结果并制定计划?
- 为什么这个程序的结果是3 "born"?和 4 死
- 相同大小的int与BGRA并集会产生不同的结果