我想知道是否可以输入二进制数字并将它们转换回文本。例如,我会输入“01101000 01100101 01101100 01101100 01101111”,然后它会将其转换为单词“hello”。
仅仅是一些逻辑上的修正:
这里有三个步骤
幸运的是,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;
}