5

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?

Boann
  • 48,794
  • 16
  • 117
  • 146
Krushna
  • 5,059
  • 5
  • 32
  • 49

1 Answers1

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;
Sizik
  • 1,066
  • 5
  • 11