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>
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>
Share
Improve this question
edited Mar 6, 2023 at 16:33
Tim Sylvester
23.2k2 gold badges81 silver badges98 bronze badges
asked Apr 6, 2018 at 5:54
avinashavinash
1632 silver badges12 bronze badges
8
-
parseInt(color.substr(1), 16)
– Jaromanda X 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))
-> outputs16711680
... why is that not expected? – Jaromanda X Commented Apr 6, 2018 at 6:06 - @JaromandaX, he's probably looking at the signs too, where first bit is the sign. – Pranav Totla 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
Reset to default 9If 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