Javascript: convert a (hex) signed integer to a javascript value

function hexToSignedInt(hex) {
    if (hex.length % 2 != 0) {
        hex = "0" + hex;
    }
    var num = parseInt(hex, 16);
    var maxVal = Math.pow(2, hex.length / 2 * 8);
    if (num > maxVal / 2 - 1) {
        num = num - maxVal
    }
    return num;
}

function hexToUnsignedInt(hex){
    return parseInt(hex,16);
}

the first for signed integer and the second for unsigned integer


I came up with this

function hexToInt(hex) {
    if (hex.length % 2 != 0) {
        hex = "0" + hex;
    }
    var num = parseInt(hex, 16);
    var maxVal = Math.pow(2, hex.length / 2 * 8);
    if (num > maxVal / 2 - 1) {
        num = num - maxVal
    }
    return num;
}

And usage:

var res = hexToInt("FF"); // -1
res = hexToInt("A"); // same as "0A", 10
res = hexToInt("FFF"); // same as "0FFF", 4095
res = hexToInt("FFFF"); // -1

So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.


Use parseInt() to convert (which just accepts your hex string):

parseInt(a);

Then use a mask to figure out if the MSB is set:

a & 0x8000

If that returns a nonzero value, you know it is negative.

To wrap it all up:

a = "0xffeb";
a = parseInt(a, 16);
if ((a & 0x8000) > 0) {
   a = a - 0x10000;
}

Note that this only works for 16-bit integers (short in C). If you have a 32-bit integer, you'll need a different mask and subtraction.


Based on @Bart Friederichs I've come with:

function HexToSignedInt(num, numSize) {
    var val = {
        mask: 0x8 * Math.pow(16, numSize-1), //  0x8000 if numSize = 4
        sub: -0x1 * Math.pow(16, numSize)    //-0x10000 if numSize = 4
    }
    if((parseInt(num, 16) & val.mask) > 0) { //negative
        return (val.sub + parseInt(num, 16))
    }else {                                 //positive
        return (parseInt(num,16))
    }
 }

so now you can specify the exact length (in nibbles).

var numberToConvert = "CB8";
HexToSignedInt(numberToConvert, 3);
//expected output: -840