Convert binary string to ascii text?

后端 未结 2 1959
予麋鹿
予麋鹿 2021-01-06 16:58

I was wondering if it is possible to enter in binary numbers and have them translated back into text. For example I would enter \"01101000 01100101 01101100 01101100 0110111

相关标签:
2条回答
  • 2021-01-06 17:20

    Just some logical corrections:

    There are three steps here

    1. Turning the binary set into an integer
    2. Then the integer into a character
    3. Then concatenate to the string you're building

    Luckily parseInt takes a radix argument for the base. So, once you either chop the string up into (presumably) an array of strings of length 8, or access the necessary substring, all you need to do is (char)Integer.parseInt(s, 2) and concatenate.

    String s2 = "";   
    char nextChar;
    
    for(int i = 0; i <= s.length()-8; i += 9) //this is a little tricky.  we want [0, 7], [9, 16], etc (increment index by 9 if bytes are space-delimited)
    {
         nextChar = (char)Integer.parseInt(s.substring(i, i+8), 2);
         s2 += nextChar;
    }
    
    0 讨论(0)
  • 2021-01-06 17:21

    See the answer to this question: binary-to-text-in-java.

    0 讨论(0)
提交回复
热议问题