Xasun
Xasun

Reputation: 277

Convert hexadecimal color to integer in javascript

I'm trying to convert a hexadecimal color string to a int in javascript.

The color int must be the same format as VB6. I think the bytes are not in the normal order. Ex: 255 is red (#ff0000) and 16776960 is Aqua (#00ffff)

I have a function to do the inverse: (But someone in the comments told me that it's not correct)

function VBColorToHEX(i) {
    var hex = (i & 0xFF).toString(16) +
              ((i >> 8) & 0xFF).toString(16) +
            ((i >> 16) & 0xFF).toString(16) +
            ((i >> 24) & 0xFF).toString(16);

    hex += '000000';
    hex = hex.substring(0, 6);
    return "#" + hex;
}

But was unable to write a function to return to my initial value.

Can you help me?

EDIT:

I corrected my original function by padding each separate colors:

function VBColorToHEX(i) {
   var r = (i & 0xFF).toString(16);
   var g = ((i >> 8) & 0xFF).toString(16);
   var b = ((i >> 16) & 0xFF).toString(16);

   r = ('0' + r).slice(-2);
   g = ('0' + g).slice(-2);
   b = ('0' + b).slice(-2);

   return "#" + r + g + b;
}

Upvotes: 4

Views: 11678

Answers (2)

Ilya
Ilya

Reputation: 5557

function VBColorToHEX(i) {
    var hex = (i & 0xFF).toString(16) +
              ((i >> 8) & 0xFF).toString(16) +
            ((i >> 16) & 0xFF).toString(16) +
            ((i >> 24) & 0xFF).toString(16);

    hex += '000000'; // pad result
    hex = hex.substring(0, 6);
    return "#" + hex;
}

You're padding the result with zeroes instead of padding each color value. For instance if i = 657930, the string hex value is something like #0A0A0A but you'll output #AAA000 instead.

Beside, if you're extracting 4 color channels you need 8 chars and not 6.

PS for the padding, see for instance this solution.

Upvotes: 1

andi
andi

Reputation: 6522

Here's a working version of your original function, which I think will make more sense to you about how it actually works.

function VBColorToHEX(i) {
    var bbggrr =  ("000000" + i.toString(16)).slice(-6);
    var rrggbb = bbggrr.substr(4, 2) + bbggrr.substr(2, 2) + bbggrr.substr(0, 2);
    return "#" + rrggbb;
}

Then, to do the reverse, do this:

function HEXToVBColor(rrggbb) {
    var bbggrr = rrggbb.substr(4, 2) + rrggbb.substr(2, 2) + rrggbb.substr(0, 2);
    return parseInt(bbggrr, 16);
}

Upvotes: 7

Related Questions