最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parsing a little endian hex string to decimal - Stack Overflow

programmeradmin0浏览0评论

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
  • What would you call "simpler" or "easier"? I'd make only a minor change, but that is only a "I'd perfer it that way" thing: 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
  • @Thomas well I have a lot of different hex string with different lengths, doing this every time is kind of a drag – Jan Commented Jun 1, 2017 at 12:44
Add a comment  | 

2 Answers 2

Reset to default 17

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

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

发布评论

评论列表(0)

  1. 暂无评论