C - RGBA 转换未返回所需的 RGB 结果

C - RGBA Conversion Not Returning The Desired RGB Result

好的,我有一个方法,但我很难 return 获得想要的结果。所以我做了一个测试结果,它是returning一个我没想到的结果。

这是一个例子 -->

int color = 0x00FFFF00;

return 0xFF & (color >> 24) | 0xFF & (color >> 16) | 0xFF & (color >> 8);

据我所知,这应该 return:

0x00FFFF

然而,它实际上 returns:

0x0000FF

有人可以解释一下发生了什么吗?我也想知道如何正确地将32位RGBA整数转换为24位RGB整数,谢谢。

试试这个:

#include <stdio.h>
int main() {

        unsigned int x = 0x00FFFF00;
        printf("0%8.8x", (x >> 8) & 0x00FFFFFF);
}

$ cc -o shft shft.c
$ ./shft
0x0000ffff

最好把颜色设为unsigned int, 否则你可以让符号位从左边移入,但在这种情况下,我们屏蔽掉了以字节为单位的移位,但要小心。

我也发现了我做错的地方。我没有移动整数转换的红色和绿色元素以匹配 RGB 整数 --->

int color = 0x00FFFF00;

// Returns 0x0000FF
return 0xFF & (color >> 24) | 0xFF & (color >> 16) | 0xFF & (color >> 8);

这里是固定代码--->

unsigned int color = 0x00FFFF00; // Unsigned Integer to avoid shifting the Two's Complement flag into the RGB value as clearlight pointed out.

// Returns 0x00FFFF
return (0xFF & (color >> 24)) << 16 | (0xFF & (color >> 16)) << 8 | 0xFF & (color >> 8);