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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With