Search code examples
javanumberformatexception

Having trouble converting a string into an integer


public static int[] booleanToBinary(boolean[] b) {
    int[] arr = new int[b.length];
    for(int i = 0; i < b.length; i++) {
        if(b[i] == true) {
             arr[i] = 1;
        }
        else{arr[i] = 0;};
        }
    
    return arr;
}



public static int binaryToInt(boolean[] b) {
    int[] a = booleanToBinary(b);
    String c = Arrays.toString(a);
    System.out.println(c);
    int decimal = Integer.parseInt(c, 2);
    
        System.out.println(decimal);
    

    
    return decimal;
    
}

 public static void main(String[] args) {
    boolean[] test = {false, true, false, true};
    System.out.println(Arrays.toString(booleanToBinary(test)));
    System.out.println(binaryToInt(test));
    
}

Blockquote I'm trying to turn the binary value into an Integer value, and I'm trying to do that using the binaryToInt method, and an NumberExceptionFormat is happening, I know that this error happens when java cannot convert a String into an Integer, can someone help me to fix this this error


Solution

  • To convert a list of booleans to an int equivalent, try it like this. No need to use any strings or integer parsing methods.

    // 100111 the value = 39
    boolean[] b = {true, false, false, true, true, true};
    int v = binaryToInt(b);
    System.out.println(v);
    

    prints

    39
    
    • first multiply decimal by 2
    • then add 1 or 0 as appropriate.
    • continue, multiply and adding
    public static int binaryToInt(boolean[] bools) {
        int decimal = 0;
        for (boolean b : bools) {
            decimal = decimal * 2 + (b ? 1 : 0);
        }
        return decimal;
    }
    
    

    Similarly, to convert an array of booleans to an array of 1's or 0's.

    public static int[] booleanToBinary(boolean[] bools) {
        int[] arr = new int[bools.length];
        int i = 0;
        for (boolean b : bools) {
            arr[i++] = b ? 1 : 0;
        }
        return arr;
    }
    

    Note if you want to just convert your boolean array into a binary string, this will work.

    public static String booleanToBinaryString(boolean[] bools) {
        int[] arr = new int[bools.length];
        String result = "";
        for (boolean b : bools) {
            result += b ? 1 : 0;
        }
        return result;
    }
    
    System.out.println(booleanToBinaryString(b));
    

    prints

    100111