0

I need a way of getting a signed 8-bit integer from a hexadecimal value using JavaScript. So far I have tried using parseInt(value, 8) but it seems to be deprecated and I get parseInt(0xbd, 8) = 0 (when it's supposed to give -67).

How can I do this?

alvaro.delaserna
  • 539
  • 1
  • 6
  • 21
  • I gave a solution for a similar problem here: http://stackoverflow.com/a/34679269/2102748, hope it helps. – milosmns Jan 08 '16 at 14:23

2 Answers2

11

I was just searching for a solution to this in javascript. The answer from splig does not seem correct, but it lead me to the solution.

I believe you should be subtracting 256 from num when (num > 127).

var num = parseInt('ff', 16);
if (num > 127) { num = num - 256 }
alert(num);
Chris
  • 126
  • 1
  • 3
1

The second parameter of parseInt is the radix, you need 16 as it's hex because you've told it it's hex the 0x is optional.

As you're wanting to do an 8 bit signed int you'll need convert it to signed manually - try something like

var num = parseInt('bd', 16);
if (num > 127) { num = 128 - num }
alert(num);
splig
  • 371
  • 1
  • 4
  • 11