我在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>
答案 0 :(得分:6)
如果需要带符号的24位值,则该函数为
function colorToSigned24Bit(s) {
return (parseInt(s.substr(1), 16) << 8) / 256;
}
console.log(colorToSigned24Bit('#ff0000'))
&#13;
说明:
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