提取十六进制数的“部分”

6

我想编写一个函数getColor(),它可以让我从输入为long的十六进制数中提取部分。

详细信息如下:

//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比例定义的。


1
“绿色”不是一个中间值吗?请参考http://en.wikipedia.org/wiki/Rgb#The_24-bit_RGB_representation:(255, 0, 0)代表红色 (0, 255, 0)代表绿色 (0, 0, 255)代表蓝色。 - DNNX
2个回答

18

通常:

  1. 首先进行移位操作。
  2. 然后进行屏蔽操作。

例如:

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

操作的顺序有助于减少所需的掩码常量的大小,通常会导致更小的代码。

我认真考虑了DNNX的评论,并交换了组件的名称,因为顺序通常是RGB(而不是RBG)。

此外,请注意,当您在整数类型上进行操作时,这些操作与数字是否为“十六进制”无关。十六进制是一种表示数字的方式,以文本形式呈现。数字本身不是以十六进制存储的,它和计算机中的其他一切一样,都是二进制的。


4
如果可能的话,他可以将枚举改为enum Color {Red = 16, Green = 8, Blue = 0}。然后switch语句就会变得非常流畅: return (hexval >> color) & 0xff。 - quinmars

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

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

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接