Extracting "parts" of a hexadecimal number

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

Details:

//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 (ie return int value of xAB if input was 'xABCDEF') break; case Green: ; //return the 'middle' value (ie return int value of xCD if input was 'xABCDEF') break; default: //assume Blue ; //return the RIGHTmost value (ie return int value of xEF if input was 'xABCDEF') break; } } 

My "bit" is not what it used to be. I would appreciate help on this.

[Change] I changed the order of the color constants in the switch statements - no doubt, designers, CSS enthusiasts, would notice that the colors are defined (in the RGB scale) as RGB;)

+4
source share
2 answers

Generally:

  • Forward shift
  • Mask last

So for example:

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

The order of operations helps to reduce the size of the literal constants needed for masks, which usually leads to a reduction in code.

I took a DNNX comment to the heart and switched component names, since the order is usually RGB (not RBG).

Also, note that these operations have nothing to do with a number that is hexadecimal when you perform operations on an integer type. Hexadecimal is a designation, a way of representing numbers, in text form. The number itself is not stored in hexadecimal, it is binary, like everything else on your computer.

+13
source
 switch (Color) { case Red: return (hexvalue >> 16) & 0xff; case Blue: return (hexvalue >> 8) & 0xff; default: //assume Green return hexvalue & 0xff; } 
0
source

Source: https://habr.com/ru/post/1301439/


All Articles