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 what 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 ;)
Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).
Thus Hexadecimal numbers can be represented without the #x or #16r prefix code, when the input or output base has been changed to 16.
Summary of binary types: hexadecimal: A representation of 4 bits by a single digit 0..
Generally:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With