How can I convert a binary string with a width of 64-bit length in Java?

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

Long.parseLong(String s, int radix) 

but this is not suitable for my case.

The problem is that my binary string is a long int.

For example:

1111111111111111111111111111111111111111111111111111111110000101 represents -123 , but this method recognizes this as a huge positive number, it bothers me, how can I solve this problem?

Should I write a function that performs the addition?

+7
source share
4 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 
+9
source

My incredible hacking 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 one, the number is negative, so we analyze the rest of the number as positive, then do two additional magic additions, subtracting this result from Long.MAX_VALUE and adding one, and then forcibly negative back to the returned number. Otherwise, normal conversion is applied.

+2
source

You can just set the bit yourself ...

 assert string.length() == 64; long result = 0; for (int i = 0; i < 64; ++i) { char c = string.charAt(63-i); switch (c) { case '1': result |= (1L << i); break; case '0'; break; default: throw new WhateverException("bad char " + c); } } 

EDIT: I originally had 1 <i, which means the shift is done as an int. Fixed to make it long.

+1
source

I don't think the library function does what you want, but this should work:

 long num = 0L; for (int i = 0; i < 64; i++) { if (yourString.charAt(i) == '1') { num ^= 1L << (63 - i); } } 

Of course, you should check that the string is 64 in length and contains only 0 and 1.

0
source

All Articles