Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert array of integers into hex string and vice versa in javascript

I have array of 32 bit integers in javascript. How to convert it into the Hex string and again build the same 32 bit integer array from that Hex string when required?

hexString = yourNumber.toString(16); can be used to convert number to hex but when array of numbers is converted into Hex string (it will be continuous or separated by some character) then how do I get back array of numbers from that string?

like image 485
vaichidrewar Avatar asked Dec 03 '22 06:12

vaichidrewar


2 Answers

If you want to do it without commas

[3546,-24,99999,3322] ==> "00000ddaffffffe80001869f00000cfa"

then you can build up the string using 8 hex-digits for each number. Of course, you'll have to zero-pad numbers that are shorter than 8 hex-digits. And you'll have to ensure that the numbers are encoded with twos-compliment to properly handle any negative values.

Here's how to do that:

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 that shows the above example.

like image 100
Lee Avatar answered Feb 16 '23 04:02

Lee


Here you go:

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

http://jsfiddle.net/whT2m/

ADDENDUM

The OP asked about using a separator other than a comma. Only a small tweak is needed. Here is a version using the semicolon:

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

http://jsfiddle.net/DEbUs/

like image 44
Ray Toal Avatar answered Feb 16 '23 04:02

Ray Toal