XOR operation and BitCount in Java on Long variables returns java.lang.NumberFormatException

254 views Asked by At

I am trying to do a XOR operation on two 64 bits Long variables in Java. The problem is that it fails when I add more than 16 bits in a variable.

For instance this works and returns 7:

Long h1 = Long.parseLong("1100001101001101");
Long h2 = Long.parseLong("1100001101000001");
System.out.println(Long.bitCount(h1 ^ h2));

If I increase the value of h1 and h2 to:

Long h1 = Long.parseLong("11000110000110100110101101001101");
Long h2 = Long.parseLong("11000011100001101001101101000001");

I get an error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11000110000110100110101101001101"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:592)
at java.lang.Long.parseLong(Long.java:631)

Same if I double it (64 bits what I would want to compute):

Long h1 = Long.parseLong("1100011100011000011010011010110100110110000110100110101101001101");
Long h2 = Long.parseLong("1100001110001100001101001101011010011011100001101001101101000001");

Any help on why this fails above 16 bits?

2

There are 2 answers

2
Eran On

Long.parseLong("11000110000110100110101101001101") attempts to parse the String as decimal number, and this number is too large to fit in a long variable.

To parse the String as a binary number you need to specify the radix:

Long.parseLong("11000110000110100110101101001101",2);

BTW, Long.parseLong returns a long, so I'd either assign it to a long:

long h1 = Long.parseLong("11000110000110100110101101001101",2);

or use Long.valueOf:

Long h1 = Long.valueOf("11000110000110100110101101001101",2);
0
Vinit Chauhan On

Convert this binary string to a number and then do the XOR. like convert 0110 -> 6, 1000 -> 8 and so on... then it won't give any exception.

public class Bin2Num {
    public static void main(String[] args) {
        long num1 = Bin2Num.funcBin2Long(args[0]);
        long num2 = funcBin2Long(args[1]);

        System.out.println("Num1 : " + num1);
        System.out.println("Num2 : " + num2);
        System.out.println("Num1 XOR num2 : " + (long)(num1 ^ num2));
    }

    public static long funcBin2Long(String str) {
        long answer = 0;
        for(int i = str.length() - 1, j = 0; i >= 0; i--, j++) {
            if(str.charAt(i) == '1') answer += Math.pow(2, j);
        }
        return answer;
    }
}