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

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.

Leave a Comment