Java 8: Why can't I parse this binary string into a long?

旧时模样 提交于 2019-12-01 12:15:15

Quoting Long.toBinaryString(i) Javadoc (emphasis mine):

Returns a string representation of the long argument as an unsigned integer in base 2.

And quoting Long.parseLong(s, radix) (emphasis mine):

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

The problem comes from the fact that toBinaryString returns a unsigned value whereas parseLong expects a signed value.

You should use Long.parseUnsignedLong(s, radix) instead:

String binaryString = Long.toBinaryString(Long.MIN_VALUE);
long smallestLongPossibleInJava = Long.parseUnsignedLong(binaryString, 2);

Note that this is actually explicitely said in toBinaryString Javadoc:

The value of the argument can be recovered from the returned string s by calling Long.parseUnsignedLong(s, 2).

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