将一串二进制解析为文本/字符 [英] Parsing a string of binary into text/characters
问题描述
我可能忽视了一些愚蠢的事情,但我从来没有在代码中处理过二进制文件,并认为在加密程序中练习它是个好主意。
长话短说,我能够将字符串转换为二进制(以字符串的形式),但无法弄清楚如何反向。
I am probably overlooking something silly, but I've never had to deal with binary in code and thought it'd be a good idea to practice it in an encryption program, for kicks. Long story short, I'm able to convert a string into binary (in the form of a string), but can't figure out how to do the reverse.
现在,我有这样的事情:
Right now, I have something like this:
public static String bytesToString(String bytes){
int i = bytes.length()/8;
int pos = 0;
String result = "";
for(int j=0; j<i; j++){
String temp = bytes.substring(pos,pos+8);
byte b = (byte) Integer.parseInt(temp);
result = result + Byte.toString(b);
pos++;
}
System.out.println("Result: " + result);
return result;
}
我认为字节被解析为文字数字。我错过了什么?
编辑:为了澄清,我先前已经将一串文本解析成位并将它们写成字符串。我想将此字符串拆分为字节并将其解析为字母。这将需要011010000110010101111001并返回嘿。
I think the bytes are being parsed as literal numbers. What am I missing? To clarify, I will previously have parsed a string of text into bits and written them to a string. I want to split this string into bytes and parse them back into letters. It would take "011010000110010101111001" and return "hey".
推荐答案
如何使用 Integer.parseInt(文字,2)
?如,
How about using Integer.parseInt(text, 2)
? As in,
public static int binaryToInt(String binary)
{
return Integer.parseInt(binary, 2);
}
我不知道为什么你的 binaryToString
方法都需要和返回一个字符串。
I'm not sure why your binaryToString
method both takes and returns a string.
这篇关于将一串二进制解析为文本/字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!