Wrapper's parseXXX() for signed binary misunderstanding

痴心易碎 提交于 2019-12-23 12:13:16

问题


Let's take Byte.parseByte() as an example as one of the wrappers' parseXXX().

From parseByte(String s, int radix)'s JavaDoc:

Parses the string argument as a signed byte in the radix specified by the second argument.

But that's not quite true if radix = 2. In other words, the binary literal of -127 is 10000000:

byte b = (byte) 0b10000000;

So the following should be true:

byte b = Byte.parseByte("10000000", 2);

but unfortunately, it throws NumberFormatException, and instead I have to do it as follows:

byte b = Byte.parseByte("-111111", 2);

where parseByte() parses the binary string as a sign-magnitude (the sign and the magnitude), where it should parse as a signed binary (2's complement, i.e. MSB is the sign-bit).

Am I wrong about this?


回答1:


Am I wrong about this?

Yes. The Javadoc says nothing about 2's-complement. Indeed, it explicitly states how it recognises negative values (i.e. a - prefix, so effectively "human-readable" sign-magnitude).

Think about it another way. If parseByte interpreted radix-2 as 2's-complement, what would you want it to do for radix-10 (or indeed, any other radix)? For consistency, it would have to be 10's-complement, which would be inconvenient, I can assure you!




回答2:


This is because for parseByte "10000000" is a positive value (128) which does not fit into byte values range -128 to 128. But we can parse two's comlement binary string representation with BigInteger:

byte b = new BigInteger("10000000", 2).byteValue()

this gives expected -128 result



来源:https://stackoverflow.com/questions/14937948/wrappers-parsexxx-for-signed-binary-misunderstanding

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