2010-02-16 42 views
4

我想編寫一個函數的getColor(),讓我來提取輸入爲長提取一個十六進制數

十六進制數部分的「部分」的具體內容如下:

//prototype and declarations 
enum Color { Red, Blue, Green }; 

int getColor(const long hexvalue, enum Color); 

//definition (pseudocode) 
int getColor(const long hexvalue, enum Color) 
{ 
    switch (Color) 
    { 
     case Red: 
     ; //return the LEFTmost value (i.e. return int value of xAB if input was 'xABCDEF') 
     break; 

     case Green: 
     ; //return the 'middle' value (i.e. return int value of xCD if input was 'xABCDEF') 
     break; 

     default: //assume Blue 
     ; //return the RIGHTmost value (i.e. return int value of xEF if input was 'xABCDEF') 
     break; 
    } 
} 

我的'搗蛋'不是以前的樣子。我將不勝感激這方面的一些幫助。

[編輯] 我改變了switch語句的顏色常量的順序 - 毫無疑問,任何設計師,CSS愛好者在那裏會注意到,顏色定義(在RGB比例)爲RGB)

+1

是不是真的__Green__中間值? 見http://en.wikipedia.org/wiki/Rgb#The_24-bit_RGB_representation: (255,0,0)是紅色 (0,255,0)是綠色 (0,0,255)是藍色的 – DNNX

回答

13

一般:

  1. 移位第一
  2. 面膜最後

所以,舉例來說:

case Red: 
     return (hexvalue >> 16) & 0xff; 
case Green: 
     return (hexvalue >> 8) & 0xff; 
default: //assume Blue 
     return hexvalue & 0xff; 

操作的排序有助於減少掩碼所需的字面常量的大小,這通常會導致較小的代碼。

我把DNNX的評論放在心上,並且切換了組件的名稱,因爲順序通常是RGB(不是RBG)。

此外,請注意,當您對整數類型進行操作時,這些操作與數字爲「十六進制」無關。十六進制是一種符號,代表數字,以文本形式。數字本身不是以十六進制存儲的,它與計算機中的其他所有內容一樣是二進制的。

+3

如果可能,他還可以將枚舉更改爲枚舉顏色{紅色= 16,綠色= 8,藍色= 0}。並且開關將變成超流體: return(hexval >> color)&0xff – quinmars

0
switch (Color) 
{ 
    case Red: 
    return (hexvalue >> 16) & 0xff; 

    case Blue: 
    return (hexvalue >> 8) & 0xff; 

    default: //assume Green 
    return hexvalue & 0xff; 

}