[英]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.