Convert RBG to HEX

How to convert RGB color to HEX in AS3 ?. For example: R = 253 G = 132 B = 58.

Tks.

+5
source share
4 answers

Robusto's solution is too slow.

Since the RGB values ​​are stored as follows:

8b Red | 8b Green | 8b Blue

And the value 0-255 (this is not a coincidence) also has 8b, you can use left bitwise shifts to get the value int, and THEN you can get the hex (almost 3 times faster). So:

var intVal:int = red << 16 | green << 8 | blue;
var hexVal:String = intVal.toString(16);
hexVal = "#" + (hexVal.length < 6 ? "0" + hexVal : hexVal);

Where are the red, green, and blue RGB values ​​that you want to convert.

+17
source

Convert RGB numbers to hexadecimal values ​​and connect them.

var hexVal = (253).toString(16) + (132).toString(16) + (58).toString(16);
hexVal = "#" + hexVal;
// returns "#fd843a"

It is less elegant than it should be, but it should give you this idea.

+3

Aurel300 - , . Robusto, , .

, -, :

var intVal:int = red * 0x10000 + green * 0x100 + blue;

or, if you think that hexadecimal notation will cause confusion.

var intVal:int = red * 65536 + green * 256 + blue;

I posted this just to show you another way to get the hexadecimal value (which gives a clearer idea of ​​how the components work and, it seems to me, add up to the final value), but, as I said, Aurel300 code.

+3
source

Most color applications require a six-digit hex code:

function RGBtoHEX(r, g, b) { 
    var s = (r << 16 | g << 8 | b).toString(16); 
    while(s.length < 6) s="0"+s;
    return "#"+s;
}
+2
source

All Articles