Sometimes we need to convert an integer value which is in decimal format to the hexadecimal string in JavaScript or need a decimal value from a given hexadecimal string.
有时,我们需要将十进制格式的整数值转换为JavaScript中的十六进制字符串,或者需要给定十六进制字符串中的十进制值 。
Read more: How to assign decimal, octal and hexadecimal values to the variables in JavaScript?
: 如何为JavaScript中的变量分配十进制,八进制和十六进制值?
In such cases, we can convert a decimal value to the hexadecimal string by using the number.toString(16) and hexadecimal string to the decimal by using hex_string.parseInt(16).
在这种情况下,我们可以通过使用number.toString(16)和十六进制字符串到十进制通过使用hex_string.parseInt(16) 转换成十进制值以十六进制字符串 。
In both cases, 16 is the base to the number system that says that target or source value format is hexadecimal.
在这两种情况下,16是基座到数字系统 ,指出目标或源值格式是十六进制。
Example:
例:
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var a = 10;
var b = 12345;
document.write("a = " + a.toString(16) + "<br>");
document.write("b = " + b.toString(16) + "<br>");
//conver hexadecimal string to the int again
var hex = "0A"; //hex of 10
var dec = parseInt(hex,16);
document.write("dec = " + dec + "<br>");
</script>
</body>
</html>
Output
输出量
a = a
b = 3039
dec = 10
翻译自: https://www.includehelp.com/code-snippets/convert-decimal-to-hexadecimal-and-vice-versa-in-javascript.aspx