6

I have a binary string like "11100011" and I want to convert it into a byte. I have a working example in Java like below:

byte b1 = (byte)Integer.parseInt("11100011", 2);
System.out.println(b1);

Here the output will be -29. But if I write some similar code in JavaScript like below:

parseInt('11100011', 2);

I get an output of 227.

What JavaScript code I should write to get the same output as Java?

0

1 Answer 1

6

Java is interpreting the byte as being a signed two's-complement number, which is negative since the highest bit is 1. Javascript is interpreting it as unsigned, so it's always positive.

Try this:

var b1 = parseInt('11100011', 2);
if(b1 > 127) b1 -= 256;
Sign up to request clarification or add additional context in comments.

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.