2011-03-27 120 views
2

我想知道是否可以输入二进制数字并将它们翻译回文本。例如,我将输入“01101000 01100101 01101100 01101100 01101111”,并将它转换为“hello”一词。将二进制字符串转换为ASCII文本?

+3

http://stackoverflow.com/questions/4211705/binary-to-text-in-java的副本 – CoolBeans 2011-03-27 22:56:21

回答

5

只是一些逻辑更正:

这里有

  1. 三个步骤打开二元集到一个整数
  2. 然后整成一个字符
  3. 然后串连成字符串你” re building

幸运的是parseInt需要radix参数为基地。因此,一旦您将字符串切成(大概)长度为8的字符串数组,即可访问必要的子字符串,您只需要(char)Integer.parseInt(s, 2)并连接即可。

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; 
} 
相关问题