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

前端 未结 1 1957
借酒劲吻你
借酒劲吻你 2021-01-16 06:43

Long story short, I was messing around with some basic genetic algorithm stuff in Java. I was using a long to store my genes, but I was using binary strings for

1条回答
  •  生来不讨喜
    2021-01-16 07:28

    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).

    0 讨论(0)
提交回复
热议问题