Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR & Associates.

Katrin and Jim

Month List

Parse a little-endian

by jim Jan 01, 2011 3:44 PM
littleindian

What? No, e-n-d-i-a-n. In the computer world, it’s not unusual to find integers represented in reverse byte order, with the least significant digit first. For example, the hex representation FF01 might be two very different numbers, depending on whether it is big-endian (the way we’re used to seeing them in base 10):

base 16:            FF    01
base 10:           255   001
times position:    2^8   2^0
add to get int:  65280 +   1  =  65281

or little-endian:

base 16:            FF    01
base 10:           255   001
times position:    2^0   2^8
add to get int:    255 + 256  =  511

The javascript parseInt() method assumes a big-endian representation in the string passed to it. Here’s a method that parses a little-endian hex string.

function parseLittleEndian(hex) {
    var result = 0;
    var pow = 0;
    while (hex.length > 0) {
        result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
        hex = hex.substring(2, hex.length);
        pow += 8;
    }
    return result;
};

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading