Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I convert a 64-width binary string to long in Java?

I want to convert a 64-width binary string to long, there is a static method:

Long.parseLong(String s, int radix)

to do this, but it isn't suitable for my case.

The problem is my binary string is a machine-style long int.

For example:

1111111111111111111111111111111111111111111111111111111110000101 represents -123, but this method recognize it as a huge positive number, this troubles me, how could I solve this problem?

Must I write a function that does the complement?

like image 632
Sefier Tang Avatar asked Dec 02 '11 06:12

Sefier Tang


2 Answers

You can use BigInteger

public static void main(String... args) {
    String s = "1111111111111111111111111111111111111111111111111111111110000101";
    long l = parseLong(s, 2);
    System.out.println(s +" => " + l);

    String s2 = s.substring(1);
    long l2 = parseLong(s2, 2);
    System.out.println(s2 +" => " + l2);
}

private static long parseLong(String s, int base) {
    return new BigInteger(s, base).longValue();
}

prints

1111111111111111111111111111111111111111111111111111111110000101 => -123
111111111111111111111111111111111111111111111111111111110000101 => 9223372036854775685
like image 106
Peter Lawrey Avatar answered Sep 21 '22 13:09

Peter Lawrey


My incredibly hacked-together solution, tested only on your case:

public static long makeLong(String input) {
    if(input.substring(0,1).equals("1")) {
        return -1 * (Long.MAX_VALUE - Long.parseLong(input.substring(1), 2) + 1);
    } else {
        return Long.parseLong(input, 2);
    }
}

Basically, if the first bit is a one, the number is negative, so we parse the rest of the number as a positive, then do some two's complement magic by subtracting that result from Long.MAX_VALUE and adding one, then forcing the negative back onto the number returned. Otherwise, the normal conversion applies.

like image 29
Tim Avatar answered Sep 25 '22 13:09

Tim