二进制的处理比较复杂,需要熟悉二进制,解码的过程就是编码的逆过程,因为用到map 所以也要逆变一下。
第一步代码
private static String toBinaryString(boolean flag,byte encode) {//这个方法涉及到二进制的问题,和数据结构无关
int temp = encode;
if (flag) {
temp |= 256;
}
String word = Integer.toBinaryString(temp);//生成的是补码。
if (flag) {
return word.substring(word.length() - 8);//这个如果变成索引的过程是两步, 先-1 到最后一个索引,再-7 到倒数第八个索引。 取最后八个。
}else {
return word;
}
}
第二步
private static byte [] decode(byte[] encode, HashMap<Byte, String> codes) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < encode.length; i++) {
boolean flag = (i == encode.length - 1);
String word = toBinaryString(!flag, encode[i]);
stringBuilder.append(word);
}
System.out.println("stringBuilder = " + stringBuilder.length());
HashMap<String, Byte> demap = new HashMap<>();
for (Map.Entry<Byte, String> entry : codes.entrySet()) {
demap.put(entry.getValue(), entry.getKey());//这么做是为了通过String的10这种二进制来找到对应的字符用的。
}
ArrayList<Byte> res = new ArrayList<>();
for (int i = 0; i < stringBuilder.length();) {
int count = 1;
boolean flag = true;//这个和while是找到的方式
Byte b = null;
while (flag) {
String word = stringBuilder.substring(i, i + count);
b = demap.get(word);
if (b == null) {
count++;
}else {
flag = false;
}
}
res.add(b);
i += count;
}
byte[] result = new byte[res.size()];
for (int i = 0; i < result.length; i++) {
result[i] = res.get(i);
}
return result;
}