Bug? in Long.valueOf(String, radix)

Hi everyone,

I am currently programming a genetic algorithm(GA) for my work and a came across a small difficulty.

GA usually use binary strings for their internal operations. So I decided to use Double.toLongBits() to convert a double into a long and then Long.toBinaryString() to get a String to work with.

Here is the part of the code that confuses me a bit.

double d = -2.33;

long bit = Double.toLongBits(d);

String s = Long.toBinaryString(bit);

//now try and convert it back Binary Strings have radix 2

long back = Long.valueOf(s,2);

This last line always throws a NumberFormatException.

The code was only intended to show me that the conversion always works correctly in both directions.

If I use 2.33 instead of -2.33 it works.

Am I making a mistake or is this a bug?

Thanks for any remarks!

[882 byte] By [crazy_scientist7375] at [2007-9-30 20:59:51]
# 1

parseLong() interprets that as an overflow. Which is what it really is.

Roll your own ascii-to-long that ignores overflow (not tested):

public static long binaryAtol(String s)

{

long value = 0;

for (int n = 0; n < s.length(); n++) {

value <<= 1;

char c = s.charAt(n);

if (c == '1')

value++;

else if (c != '0')

throw new NumberFormatException("not a binary digit: \"" + c + "\"");

}

return value;

}

sjasja at 2007-7-7 2:32:04 > top of Java-index,Administration Tools,Sun Connection...
# 2
Thanks, that does the trick.
crazy_scientist7375 at 2007-7-7 2:32:04 > top of Java-index,Administration Tools,Sun Connection...