我已将某些字符转换为二进制。现在我想将它们转换回原始字符。任何人都可以告诉我该怎么做?将二进制字符串转换为字符
这是我的代码转换为二进制字符。
string = Integer.toBinaryString(c);
其中c
是char类型。所以,当我将char 'a'
转换为二进制文件时,我得到了类似这样的内容 - 1101101
我已将某些字符转换为二进制。现在我想将它们转换回原始字符。任何人都可以告诉我该怎么做?将二进制字符串转换为字符
这是我的代码转换为二进制字符。
string = Integer.toBinaryString(c);
其中c
是char类型。所以,当我将char 'a'
转换为二进制文件时,我得到了类似这样的内容 - 1101101
我不确定它在android中的工作原理,但是您是否试过简单的投射?
byte b = 90; //char Z
char c = (char) b;
我试过了,但没有奏效。 –
使用Integer.parseInt(String s, int radix)
有基数= 2
(二进制)到String
转化为int
,然后投了int
到char
,像这样:
int parseInt = Integer.parseInt(your_binary_string, 2);
char c = (char)parseInt;
幸运的是,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;
}
你是如何从字符生成二进制文件? –
post some working codfe –
http://stackoverflow.com/questions/833709/converting-int-to-char-in-java [1]:http://stackoverflow.com/questions/833709/converting- int-char-in-java –