Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I know that converting a decimal to binary with Integer.toBinaryString(355) = 0000000101100011 and Integer.toBinaryString(-355) = 1111111010011101 (where I take the lower 16 bits of the 32 bit result).

What I would like to do is the other way and take a 16-bit twos's complement binary string and to convert to decimal.

i.e.

0000000000110010 =  50
1111111111001110 = -50

Rather than 1111111111001110 = 65486

How would I do this? Thanks in advance.

share|improve this question

marked as duplicate by karthikr, rgettman, SteveP, Frank Shearar, Griwes Apr 5 at 19:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 1 down vote accepted

You need to read the result into short.

short res = (short)Integer.parseInt("1111111111001110", 2);
System.out.println(res);

This prints -50.

share|improve this answer
Thanks it did the trick! – omegaFlame Apr 5 at 15:43

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