Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a little endian hex string to decimal

I have an little endian hex string that needs to be converted to a decimal in JavaScript.

Example hex string: "12AB34CD" To get the correct value it need to swap the bytes to this: "CD34AB12"

Currently I just swap the bytes using substring and then use parseInt().

var string = "12AB34CD";
var parsedInt = parseInt("0x" + string.substring(6,8) + string.substring(4,6)+ string.substring(2,4) + string.substring(0,2);

I have lots of data with unknown lenght to parse, so I was wondering if there is a better way.

like image 841
Jan Avatar asked May 31 '17 14:05

Jan


1 Answers

You can use something like this to swap the bytes:

var endian = "12AB34CD";

var r = parseInt('0x'+endian.match(/../g).reverse().join(''));

console.log(r); // Decimal
console.log(r.toString(16).toUpperCase());  // Hex
like image 81
abhishekkannojia Avatar answered Nov 02 '22 23:11

abhishekkannojia