public String convertBinaryToString(String binary){
String result = "";
for (int i = 0; i < binary.length(); i += 8) {
int charCode = Integer.parseInt(binary.substring(i,i+7), 2);
result += new Character((char) charCode).toString();
}
// String(binary.getBytes(),0,binary.getBytes().length,"ASCII");
System.out.println(result);
return result;
}
//This is my goal but it does not work that way
for (int i = 0; i < binary.length(); i+=8) {
String num = binary.substring(i,i+7);
char c = (char)Integer.parseInt(num,2);
result += c;
}
输入:0000011010001100101110110011011001101111 输出:你好//我的输出:F] 7
答案 0 :(得分:0)
Interger.parseInt(String nam,int radix)其中radix = 2表示二进制,这是用于转换为整数而不是类型转换为char你得到你的答案。
int x = Integer.parseInt(binary,2); char c =(char)x;
答案 1 :(得分:0)
<强>更新强>
首先你输入的内容不正确!!至少前两个不是 打印。对于“你好”,正确的二进制表示是:
01101000 01100101 01101100 01101100 01101111
您可以通过Integer.parseInt( String s, int radix )
方法将String直接解析为Integer,其中radix指定要解析的数字的基数。由于您要解析二进制数,因此应使用radix = 2.然后将其转换为char。
示例:
String num = "01000001"; // char 'A' in binary ( decimal 65 )
int value = Integer.parseInt( num, 2 ); // parses string to int ( 65 )
char character = (char)value; // parses int (65) to char ('A')
或简称:
String num = "01000001";
char c = (char) Integer.parseInt(num, 2);