1

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?

1

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.