Reputation: 6140
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?
Upvotes: 6
Views: 5844
Reputation: 1066
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;
Upvotes: 6