[英]Converting a binary string to an ascii string, the long way (No API Functions)
I had an interview recently and discovered that I'd forgotten some of the basics. 我最近接受了一次采访,发现我忘记了一些基本知识。 I've been playing around again and have written a function that will take a binary string (there is no validation yet) and returns the ascii representation of said string.
我一直在玩耍,并编写了一个函数,该函数将采用二进制字符串(尚无验证)并返回所述字符串的ascii表示形式。
I'm looking for advice or tips on how it could be improved. 我正在寻找有关如何进行改进的建议或技巧。 I don't want to use any of the API functions, this is more of a playground scenario in which I might be able to learn something.
我不想使用任何API函数,这更像是一个游乐场场景,在其中我可以学习一些东西。
Thanks for any help. 谢谢你的帮助。
Sample output: 样本输出:
01101000 01100101 01101100 01101100 01101111
104
101
108
108
111
hello
public static String convertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.replaceAll("\\s", "").toCharArray();
int [] mapping = {1,2,4,8,16,32,64,128};
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum = 0;
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += mapping[idx];
}
idx++;
}
System.out.println(sum);//debug
sb.append(Character.toChars(sum));
}
return sb.toString();
}
You don't need an array with the powers of two - the computer already knows them and you can use 1<<k
to get the k-th power of two. 您不需要具有2的幂的数组-计算机已经知道它们了,您可以使用
1<<k
来获得2的k次幂。 However you don't need that either. 但是,您也不需要。 Here is a short function to parse int from a char array that is the binary representation of a number.
这是一个简短的函数,用于从char数组中解析int,该char数组是数字的二进制表示形式。 With a little modification the code will work for any base up to 10.
稍加修改,该代码即可在不超过10的任何基数下工作。
public static int parseBinary(char[] chars) {
int res = 0;
for (int i = 0; i < s.length; ++i) {
res *= 2;
if (chars[i] == '1') {
res += 1;
}
}
return res;
}
Using this function you can simplify your code significantly. 使用此功能可以大大简化代码。
If you want a more java8-ish solution: 如果您想要更多的java8-ish解决方案:
public static String convertBinaryStringToString(String string) {
return stream(string.split("\\s+"))
.mapToInt(s -> s.chars().reduce(0, (x, y) -> (char) (x * 2 + (y-'0'))))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.