2010-02-16 47 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; 

}