[英]Unsigned Int to RGB Value in C
我一直在用C语言编写一些代码,将三个整数转换为它们的rgb值(红色,绿色,蓝色),但是它不起作用,我不知道为什么。 基本上,代码使用getchar()方法读取三个不同的整数(我试图仅使用getchar(),而没有其他方法)。 这是我的代码:
#include <stdio.h>
#include <string.h>
// functions
void getRGB(unsigned int x);
// input array
unsigned char data[20];
int rounds = 0;
unsigned int num1, num2, num3;
int main(void)
{
int i=0;
int c;
printf("Enter three integers between 0 and 2^32-1\n");
while(( c = getchar() ) != EOF)
{
if(c == '-')
{
puts("Negative numbers are NOT allowed, please try again.");
return 0;
}
while(isspace(c))
{
c=getchar();
}
while ((isdigit(c)))
{
data[i] = c;
i++;
c=getchar();
}
rounds++;
if (rounds == 1)
{
num1 = atoi(data);
memset(data, 0, 20);
i = 0;
}
else if(rounds ==2)
{
num2 = atoi(data);
memset(data, 0, 20);
i = 0;
}
else if(rounds ==3)
{
num3 = atoi(data);
break;
}
}
getRGB(num1);
getRGB(num2);
getRGB(num3);
return 0;
}
void getRGB(unsigned int x)
{
unsigned int red = (x & 0xff000000) >> 24;
unsigned int green = (x & 0x00ff0000) >> 16;
unsigned int blue = (x & 0x0000ff00) >> 8;
printf("num is %u == rgb (%u, %u, %u) \n", x, red, green, blue);
}
任何帮助将不胜感激,因为我完全陷入了困境!
您提供的getRGB
函数会丢弃最低有效的8位。 更具体地说,假定根据以下布局,RGB分量存储在位8至31(其中位0是最低有效位)中:
- Red component : bits 24-31 (hexadecimal mask `0xff000000`)
- Green component : bits 16-23 (hexadecimal mask `0x00ff0000`)
- Blue component : bits 8-15 (hexadecimal mask `0x0000ff00`)
因此,对于具有十六进制表示形式0x000000EA
的234的测试输入值,由于位8至31均为零,因此对应的输出将为RGB =(0,0,0)。 另一方面,给定转换后的结果,将导致RGB =(0,0,234)的测试输入值将为十六进制的0x0000EA00
或等效的十进制256 * 234 = 59904。
另外,如果您想对RGB分量使用24个最低有效位,则需要将转换更新为:
unsigned int red = (x & 0x00ff0000) >> 16;
unsigned int green = (x & 0x0000ff00) >> 8;
unsigned int blue = (x & 0x000000ff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.