将整数转换为十六进制转义序列

时间:2018-04-12 04:31:49

标签: javascript

如何将整数转换为十六进制转义序列格式:

a = 1;  

到预期结果:

b = '\x00\x00\x00\x01';

任何想法?

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案(假设我理解你的问题):

var dInput = document.getElementById("d");
var xInput = document.getElementById("x");
var pInput = document.getElementById("p");
var uInput = document.getElementById("u");
var cInput = document.getElementById("c");

dInput.onchange = onChange;
dInput.onkeyup = onChange;
dInput.onclick = onChange;
dInput.onchange();

function onChange () {
  var d = parseInt(this.value, 10); // decimal
  var x = d.toString(16).toUpperCase(); // hexadecimal
  var p = "00000000".slice(x.length) + x; // padded
  var u = p.replace(/([0-9a-f]{2})/gi, "\\x$1"); // unicode
  xInput.value = x;
  pInput.value = p;
  uInput.value = u;
  cInput.value = String.fromCharCode(d);
};
<p>Try 10, 49, 65 and 97.</p>
<input id="d" type="number" min="0" step="1" value="1"> decimal
<br><input id="x" type="text" disabled> hexadecimal
<br><input id="p" type="text" disabled> padded
<br><input id="u" type="text" disabled> unicode
<br><input id="c" type="text" disabled> character