开发者

Extracting 'parts' of a hexadecimal number

I want to write a function getColor() that allows me to extract parts of a hexadecimal number entered as a long

The details are as follows:

//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;
    }
}

My 'bit twiddling' isn't wha开发者_如何学运维t it used to be. I would appreciate some help on this.

[Edit] I changed the ordering of the color constants in the switch statements - no doubt any designers, CSS enthusiasts out there would have noticed that colors are defined (in the RGB scale) as RGB ;)


Generally:

  1. Shift first
  2. Mask last

So, for instance:

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

The ordering of the operations help cut down on the size of the literal constants needed for the masks, which generally leads to smaller code.

I took DNNX's comment to heart, and switched the names of the components since the order is typically RGB (not RBG).

Furthermore, please note that these operations have nothing to do with the number being "hexadecimal", when you're doing operations on an integer type. Hexadecimal is a notation, a way of representing numbers, in textual form. The number itself is not stored in hex, it's binary like everything else in your computer.


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

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

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜