我已将某些字符转换为二进制字符。现在我想将它们转换回原始字符。有谁能告诉我怎么做?
这是我将代码转换为字符的代码。
string = Integer.toBinaryString(c);
其中c
是char类型。因此,当我将char 'a'
转换为二进制时,我会得到类似这样的内容 - 1101101
答案 0 :(得分:4)
使用基数= 2
( for binary )的Integer.parseInt(String s, int radix)
将String
转换为int
,然后转换int
} char
,像这样:
int parseInt = Integer.parseInt(your_binary_string, 2);
char c = (char)parseInt;
答案 1 :(得分:1)
幸运的是,Java API提供了一种将二进制字节转换回原始字符的相当简单的方法。
String char = (char)Integer.parseInt(string, 2)
字符串是二进制代码的一个字节(8位)。 2表示我们目前处于基数2.为此,您需要以8位部分提供二进制文件的上述代码块。
但是,函数Integer.toBinaryString(c)并不总是以8的块返回。这意味着你需要确保你的原始输出都是8的倍数。
它最终会看起来像这样:
public String encrypt(String message) {
//Creates array of all the characters in the message we want to convert to binary
char[] characters = message.toCharArray();
String returnString = "";
String preProcessed = "";
for(int i = 0; i < characters.length; i++) {
//Converts the character to a binary string
preProcessed = Integer.toBinaryString((int)characters[i]);
//Adds enough zeros to the front of the string to make it a byte(length 8 bits)
String zerosToAdd = "";
if(preProcessed.length() < 8) {
for(int j = 0; j < (8 - preProcessed.length()); j++) {
zerosToAdd += "0";
}
}
returnString += zerosToAdd + preProcessed;
}
//Returns a string with a length that is a multiple of 8
return returnString;
}
//Converts a string message containing only 1s and 0s into ASCII plaintext
public String decrypt(String message) {
//Check to make sure that the message is all 1s and 0s.
for(int i = 0; i < message.length(); i++) {
if(message.charAt(i) != '1' && message.charAt(i) != '0') {
return null;
}
}
//If the message does not have a length that is a multiple of 8, we can't decrypt it
if(message.length() % 8 != 0) {
return null;
}
//Splits the string into 8 bit segments with spaces in between
String returnString = "";
String decrypt = "";
for(int i = 0; i < message.length() - 7; i += 8) {
decrypt += message.substring(i, i + 8) + " ";
}
//Creates a string array with bytes that represent each of the characters in the message
String[] bytes = decrypt.split(" ");
for(int i = 0; i < bytes.length; i++) {
/Decrypts each character and adds it to the string to get the original message
returnString += (char)Integer.parseInt(bytes[i], 2);
}
return returnString;
}
答案 2 :(得分:0)
我不确定它在android中有效,但你尝试过简单的演员吗?
byte b = 90; //char Z
char c = (char) b;
答案 3 :(得分:0)
以下源代码对我有用。
StringBuilder binary;
创建一个类
public String stringToBinary(String str, boolean pad) {
byte[] bytes = str.getBytes();
binary = new StringBuilder();
for (byte b : bytes)
{
binary.append(Integer.toBinaryString((int) b));
if(pad) { binary.append(' '); }
}
System.out.println("String to Binary : "+binary);
return binary.toString();
}
然后,调用 class
stringToBinary("a",true);
输出:
1000001