在 javascript 中将十六进制颜色字符串转换为整数



我用javascript编写了一个函数,将整数形式的颜色从db转换为十六进制颜色格式。但是我无法将十六进制颜色字符串转换为 int 形式。parseInt(color.substr(1), 16)也给出了不同的结果。

<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>

如果你想要一个有符号的 24 位值,函数是

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

解释:

                                                                                 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

最新更新