我在javascript中有32位整数数组。 如何将其转换为十六进制字符串 并在需要时再次从该Hex字符串构建相同的32位整数数组?
hexString = yourNumber.toString(16); 可用于将数字转换为十六进制 但是当数组数组转换为十六进制字符串(它将是连续的或由某个字符分隔)时,如何从该字符串中获取数字数组?
答案 0 :(得分:6)
如果你想不用逗号
[3546,-24,99999,3322]
==> "00000ddaffffffe80001869f00000cfa"
然后您可以使用每个数字的8个十六进制数字来构建字符串。当然,您必须填充短于8个十六进制数字的数字。并且您必须确保使用twos-compliment对数字进行编码,以正确处理任何负值。
以下是如何做到这一点:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a)); // [3546,-24,99999,3322]
// convert to hex string...
//
var b = a.map(function (x) {
x = x + 0xFFFFFFFF + 1; // twos complement
x = x.toString(16); // to hex
x = ("00000000"+x).substr(-8); // zero-pad to 8-digits
return x
}).join('');
alert("Hex string " + b); // 00000ddaffffffe80001869f00000cfa
// convert from hex string back to array of ints
//
c = [];
while( b.length ) {
var x = b.substr(0,8);
x = parseInt(x,16); // hex string to int
x = (x + 0xFFFFFFFF + 1) & 0xFFFFFFFF; // twos complement
c.push(x);
b = b.substr(8);
}
alert("Converted back: " + JSON.stringify(c)); // [3546,-24,99999,3322]
here's a jsFiddle显示了上述示例。
答案 1 :(得分:4)
你走了:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a));
var b = (a.map(function (x) {return x.toString(16);})).toString();
alert("Hex string " + b);
var c = b.split(",").map(function (x) {return parseInt(x, 16);});
alert("Converted back: " + JSON.stringify(c));
<强>附录强>
OP询问使用除逗号以外的分隔符。只需要进行一些小调整。这是使用分号的版本:
var a = [3546,-24,99999,3322];
alert("Original is " + JSON.stringify(a));
var b = (a.map(function (x) {return x.toString(16);})).join(";");
alert("Hex string " + b);
var c = b.split(";").map(function (x) {return parseInt(x, 16);});
alert("Converted back: " + JSON.stringify(c));
答案 2 :(得分:3)
var ints = [1,2,30,400];
var hexstr = "";
for(var i=0; i < ints.length; i++) {
hexstr += ints[i].toString(16) + ";";
}
document.write("Hex: " + hexstr + "<br>");
var intsback = new Array();
var hexarr = hexstr.split(";");
for(var i = 0; i < hexarr.length-1; i++) {
intsback.push(parseInt(hexarr[i], 16));
}
document.write("Integers back: " + intsback);
答案 3 :(得分:1)
以下是使用普通javascript进行转换的两个函数,这些函数应该适用于所有浏览器:
var nums = [3456, 349202, 0, 15, -4567];
function convertNumArrayToHexString(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
result.push(list[i].toString(16));
}
return(result.join(","));
}
function convertHexStringToNumArray(str) {
var result = [];
var list = str.split(/\s*,\s*/);
for (var i = 0; i < list.length; i++) {
result.push(parseInt(list[i], 16));
}
return(result);
}
var temp = convertNumArrayToHexString(nums);
temp = convertHexStringToNumArray(temp);
并且,一个有效的演示:http://jsfiddle.net/jfriend00/3vmNs/
答案 4 :(得分:1)
十六进制字符串到整数数组(例如,0E0006006200980000000000000000)
dataToNumberArr(data) {
if(data.length == 2) {
let val = parseInt(data, 16);
return [val];
} else if(data.length > 2) {
return dataToNumberArr(data.substr(0, 2)).concat(dataToNumberArr(data.substr(2)));
}
}
答案 5 :(得分:0)
答案 6 :(得分:0)
您可以调用parseInt(hexString,16)将十六进制字符串转换为整数值。