无法将字符串转换为整数

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

使用 Arrays.toString 将 0 和 1 的数组转换为字符串后,可以使用 String::replaceAll 从字符串中删除所有 non-zeros 和 non-ones:

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

然后测试:

 boolean[] test = {false, true, false, true};
System.out.println(Arrays.toString(booleanToBinary(test)));
System.out.println(binaryToInt(test));

打印:

[0, 1, 0, 1]
0101
5
5

但是,这里的位顺序是颠倒的,因为数组是从 0 到 n(从低位开始)打印的。

要将布尔值列表转换为等效的 int,请像这样尝试。无需使用任何字符串或整数解析方法。

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

打印

39
  • 先把小数乘以2
  • 然后酌情加 1 或 0。
  • 继续乘加
public static int binaryToInt(boolean[] bools) {
    int decimal = 0;
    for (boolean b : bools) {
        decimal = decimal * 2 + (b ? 1 : 0);
    }
    return decimal;
}

类似地,将布尔数组转换为 1 或 0 数组。

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;
}

请注意,如果您只想将布尔数组转换为二进制字符串,这会起作用。

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));

打印

100111