binary到string

8cdiaqws  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(395)

我有一个像 1001001 100000 1110011 1100001 1101001 1100100 100000 1100110 1110101 1100011 1101011 100000 1000111 1000001 1001110 1000101 1010011 1001000 我想把他们变成 String . 有一些源代码,我已经尝试从这个链接没有工作。每次我都会犯同样的错误。

public static String binaryToText(String binaryString) {
    StringBuilder stringBuilder = new StringBuilder();
    int charCode;
    for (int i = 0; i < binaryString.length(); i += 8) {
        charCode = Integer.parseInt(binaryString.substring(i, i + 8), 2);
        String returnChar = Character.toString((char) charCode);
        stringBuilder.append(returnChar);
    }
    return stringBuilder.toString();
}

这是错误

Process: com.binary, PID: 4784
java.lang.NumberFormatException: Invalid int: "1111001 "
    at java.lang.Integer.invalidInt(Integer.java:138)
    at java.lang.Integer.parse(Integer.java:410)
    at java.lang.Integer.parseInt(Integer.java:367)
    at com.binary.MainActivity.binaryToText(MainActivity.java:97)
js5cn81o

js5cn81o1#

问题是这组位的长度并不都相同。所以帮你自己一个忙,不要只数步 split 那根绳子 " " 并单独处理每个位组:

public static String binaryToText(String binaryString) {
    StringBuilder stringBuilder = new StringBuilder();
    int charCode;
    // Split the string
    String[] parts = binaryString.split(" ");
    // Consider each part on its own
    for (String part : parts) {
        charCode = Integer.parseInt(part, 2);
        String returnChar = Character.toString((char) charCode);
        stringBuilder.append(returnChar);
    }
    return stringBuilder.toString();
}

相关问题