简体   繁体   English

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

[英]C - RGBA Conversion Not Returning The Desired RGB Result

Okay, I have a method that I am having a difficult time with returning the desired results. 好的,我有一种方法很难返回期望的结果。 So I made a test result, and it is returning a result that I was not expecting. 因此,我做出了一个测试结果,并且返回的结果不是我所期望的。

Here is an example --> 这是一个例子->

int color = 0x00FFFF00;

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

From what I know, this should return: 据我所知,这应该返回:

0x00FFFF

However, it actually returns: 但是,它实际上返回:

0x0000FF

Can someone please explain what is happening? 有人可以解释发生了什么吗? I would also like to know how I could properly convert the 32-bit RGBA integer to the 24-bit RGB integer, thank you. 我也想知道如何将32位RGBA整数正确转换为24位RGB整数,谢谢。

I also caught what I did wrong. 我也发现自己做错了。 I was not shifting the red and green elements of the integer cast to match the RGB integer ---> 我没有移动整数转换的红色和绿色元素以匹配RGB整数--->

int color = 0x00FFFF00;

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

Here is the fixed code ---> 这是固定代码--->

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);

Try this: 尝试这个:

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

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

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

It's better if you make color an unsigned int , otherwise you can get the sign bit shifted in from the left, but in this case we're masking off the shifted in bytes, but be careful of that. 最好将color设置为unsigned int ,否则可以使符号位从左移入,但是在这种情况下,我们将掩盖移位的字节,但是要小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM