Java two's complement binary to integer [duplicate]

流过昼夜 提交于 2019-12-29 08:45:10

问题


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?


回答1:


You need to read the result into short.

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

This prints -50.




回答2:


Use a short? They occupy 16 bits.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html



来源:https://stackoverflow.com/questions/15837899/java-twos-complement-binary-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!