[英]Convert binary string to char
我已将一些字符转换为二进制。 现在我想将它们转换回原始字符。 有人可以告诉我怎么做吗?
这是我将字符转换为二进制的代码。
string = Integer.toBinaryString(c);
其中c
是字符类型。 因此,当我将字符'a'
转换为二进制时,我会得到这样的结果 - 1101101
使用Integer.parseInt(String s, int radix)
和 radix = 2
(对于 binary )将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;
}
我不确定它是否适用于 android,但是您是否尝试过简单的转换?
byte b = 90; //char Z
char c = (char) b;
以下源代码对我有用。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.