Home > Software engineering >  NumberFormatExcpetion while using Long.parseLong() to parse a base-2 number(as a string) to a base-1
NumberFormatExcpetion while using Long.parseLong() to parse a base-2 number(as a string) to a base-1

Time:02-03

So I'm trying to flip the bits of a long int, this is how I'm doing it but I'm getting the NumberFormatException. I'm converting it to a base-2 string and add zeros to the left to become a 32 char, then flip the bits, then convert it back to long of base-10.

Long n =4L;
String bits = String.format("2s", Long.toBinaryString(n)).replace(' ', '0');
bits = bits.replace("0", "3");
bits = bits.replace("1", "0");
bits = bits.replace("3", "1");
return Long.parseLong(bits.trim(), 10);

4L after converting to base 2:

00000000000000000000000000000100

after flipping all bits:, I'm getting this:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111011"

What's wrong? I checked for non-printable chars but there aren't, also I trimmed the number in case there are any extra spaces, I tried to add L at the end but nothing worked, what's the problem?

CodePudding user response:

I am not 100% sure if this is what you are looking for. This will convert a string of binary to a long. Note: I am not checking for 0's in the method. You may need to change that to suit your needs.

    public long stringBinaryToLong( final String binaryString) {
        if(binaryString == null) {
            return 0l;
        }
        // Check length for long on binary string. How many binary digits are the max length.
        // Determine this by taking log(base 2) for Long max.
        // log base 2 not available so use this technique. --> log_base2 (x) = log_base10 (x) / log_base10 (2)
        if( binaryString.length() > Math.ceil( Math.log10( (double) Long.MAX_VALUE ) / Math.log10( 2.0 ) ) ) {
            throw new IllegalStateException("string of binary digits exceeds max size for a Java long.");
        }
        double base = 2.0, power=0.0;
        long result = 0l;
        for(int index=binaryString.length() - 1; index > -1; index--) {
            if( binaryString.charAt(index) == '1') {
                result  = Math.pow(base,  power);
            }
            power  = 1.0;
        }
        return result;
    }

CodePudding user response:

So the problem was with the radix parameter of the parseLong method, radix is to specify the base of the string that I want to parse, not the output of the parse method

So the whole issue was solved by substituting this:

return Long.parseLong(bits.trim(), 10);

with this:

return Long.parseLong(bits.trim(), 2);

now, the string of bits (the input of parseLong method) is of base 2 as mentioned in the radix parameter

  •  Tags:  
  • Related