4

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?

3
  • 1
    What do you envision your hex string to look like? If you have the array [3546,-24,99999,3322] then do you want your string to be dda,-18,1869f,cfa or do you want 00000DDAFFFFFFE80001869F00000CFA? Commented Oct 6, 2011 at 4:48
  • If it takes second form then how to get back the array of 32 bit integers? I want minimum characters in the output so will first be better in which I will first have to separate out commas and then convert those to 32 bit integer? Commented Oct 6, 2011 at 4:51
  • FYI In the second form every 8 digits represents your 32-bit integer, and there is no need for a separator. The first case is fine, too. Commented Oct 6, 2011 at 4:54

8 Answers 8

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Nice addition to the set of answers. Good to see lots of alternatives.
4

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/

8 Comments

Nice functions! But if comma is not be used then what will have to be done?
The comma is safe under the precondition that all the elements in the original array are numbers. You get the comma for free by using JavaScript's Array#toString method. Would you like to use a non-comma for your separator? If so, you can replace the toString I used with an expression using join. Let me know if you would like to see an answer with a custom separator. (I am aware that jfriend00 posted an answer with a semicolon; but if you are interested in the functional approach I will be happy to add to my answer. jfriend00's is faster.)
@vaichidrewar Added a version using the semicolon instead FYI. Just about any character will do as long as it is not a hex digit or a hyphen (used for the minus sign).
@Ray You mentioned two ways in comments to question 1)With separator 2) without separator. If without separator is to be used then what will be needed?
In my original comment to your question I was asking whether you wanted to take advantage of the fact that 32-bit numbers are represented in exactly 8 hexadecimal digits so that you could pack them together. No separator is needed because the values all take up exactly 8 hex digits. To convert back you read 8 hex digits at a time. This mechanism requires that you do a lot more work though, and will take up more space when the numbers are small.
|
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);

http://jsfiddle.net/YVdqY/

Comments

1

Here are two functions to do the conversions using plain javascript that should work in all browsers:

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

And, a working demo: http://jsfiddle.net/jfriend00/3vmNs/

Comments

1

Hex string to integer array(ex, 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)));
        }
    }

Comments

0

Use this:

parseInt(hexstr, 16);

Source: http://javascript.about.com/library/blh2d.htm

Comments

0

You can call parseInt(hexString, 16) to convert a hex string to an integer value.

1 Comment

How to convert the hex string to array of 32 bit integers
0
let ints = [1,2,30,400];
let hex = parseInt(ints.reverse().map(n => n.toString(16)).join(''), 16)

If you want to use large numbers (>255) like "400" you have to add padding to every array member

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.