Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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;
share|improve this answer
    
Thank you , it's working –  Krushna Oct 17 '14 at 18:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.