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.
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.
Share Improve this question edited Jun 1, 2017 at 13:57 Jan asked May 31, 2017 at 14:41 JanJan 6027 silver badges19 bronze badges 2 |2 Answers
Reset to default 17You 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
I came up with this myself but the accepted answer is much shorter.
var hexstring = "12AB34CD";
function littleEndianHexStringToDecimal(string)
{
if(!string) return undefined;
var len = string.length;
var bigEndianHexString = "0x";
for(var i = 0; i < len/2; i++)
{
bigEndianHexString += string.substring((len-((i+1)*2)),(len-(i*2)));
}
return parseInt(bigEndianHexString);
}
console.log(littleEndianHexStringToDecimal(hexstring));
parseInt(string.substr(6,2) + string.substr(4,2) + string.substr(2,2) + string.substr(0,2), 16);
– Thomas Commented May 31, 2017 at 15:22