2014-09-11 87 views
1

我一直在C中的一些代碼將三個整數轉換爲它們的rgb值(紅色,綠色藍色),但它不工作,我不明白爲什麼。基本上,代碼使用getchar()方法讀取三個不同的整數(我試圖只使用getchar()而沒有其他)。這裏是我的代碼:無符號整數到RGB值在C

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

} 

任何幫助將不勝感激,因爲我完全難倒!

+0

,而不是「它不工作」,說什麼你得到你期待什麼 – 2014-09-11 02:03:22

+0

你是對的。例如,當我輸入234時,我期望得到(0,0,234)的rgb值。相反,我收到(0,0,0)。 – MattKos 2014-09-11 02:04:37

+0

您提供的轉換會丟棄最不重要的8位(這是您示例中唯一使用的) – SleuthEye 2014-09-11 02:06:49

回答

2

您提供的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`) 

因此,對於具有十六進制表示的234測試輸入值0x000000EA,相應的輸出將是RGB =(0,0,0),因爲比特8到31全部爲零。另一方面,給定發佈的轉換, 將導致RGB =(0,0,234)的測試輸入值將以十六進制0x0000EA00或等效地以十進制256 * 234 = 59904表示。

或者,如果你想用24個最低顯著位的RGB分量,你將需要更新轉換到:

unsigned int red = (x & 0x00ff0000) >> 16; 
unsigned int green = (x & 0x0000ff00) >> 8; 
unsigned int blue = (x & 0x000000ff);