2

I have written a function in javascript to convert an integer form of colour from db to hex colour format.But I am unable to convert hex colour string to int form. Also parseInt(color.substr(1), 16) is giving different result.

<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="test"></p>
<script>
function myFunction() {

    var color="#ff0000";    
    var num = -65536;
    var alphalessHexString =getHexColor(num);
    var n = alphalessHexString+"</br>";
    var ques="i want a function to convert "+color +"  to  "+num;
    document.getElementById("test").innerHTML = n+ques;
}

function getHexColor(number){
    return "#"+((number)>>>0).toString(16).slice(-6);
}

</script>

</body>
</html>
8
  • parseInt(color.substr(1), 16) Commented Apr 6, 2018 at 5:55
  • @JaromandaX result is not as expected after using parseInt(color.substr(1), 16) function/
    – avinash
    Commented Apr 6, 2018 at 5:59
  • var color="#ff0000"; console.log(parseInt(color.substr(1), 16)) -> outputs 16711680 ... why is that not expected? Commented Apr 6, 2018 at 6:06
  • @JaromandaX, he's probably looking at the signs too, where first bit is the sign. Commented Apr 6, 2018 at 6:08
  • I want function opposite to getHexColor.For example i am passing -65536 to getHexColor and getting #ff0000,what i want is function which can return me -65536 when i pass #ff0000 to it.
    – avinash
    Commented Apr 6, 2018 at 6:10

1 Answer 1

9

If you want a signed 24 bit value, the function is

function colorToSigned24Bit(s) {
    return (parseInt(s.substr(1), 16) << 8) / 256;
}
console.log(colorToSigned24Bit('#ff0000'))

Explanation:

                                                                                 signed 32
                                                                                 bit number
                               value    32 bit binary                            in decimal
-------------------------  ---------    ---------------------------------------  ----------
parseInt(s.substr(1), 16)   16711680    0000 0000 1111 1111 0000 0000 0000 0000    16711680
16711680 << 8             4278190090    1111 1111 0000 0000 0000 0000 0000 0000   -16777216
-16777216 / 256               -65536    1111 1111 1111 1111 0000 0000 0000 0000      -65536
2
  • Thanks buddy that's what i was looking for .
    – avinash
    Commented Apr 6, 2018 at 6:22
  • The example depends on sign extension to end up with an alpha value of FF. If you do this instead with "#00FF00" you'll get 65280 = 0000FF00 = 0000 0000 0000 0000 1111 1111 0000 0000 . If the result ends up transparent, you probably want to add ...|0xFF000000. Commented Mar 6, 2023 at 17:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.