Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

java - Binary to String in android

I have binary like 1001001 100000 1110011 1100001 1101001 1100100 100000 1100110 1110101 1100011 1101011 100000 1000111 1000001 1001110 1000101 1010011 1001000 I am trying to converted them to String. There's some source code I have tried from this link None are working. I am getting the same error everytime.

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

Here's the error

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that those group of bits are not all the same length. So do yourself a favor and, instead of counting steps just split the string on " " and handle each bit group on its own:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...