上一章中已经详细的说明了7-bit编码的实现,那么要实现解码就只是将编码还原而已。
直接上代码吧:
输入:是一个7-bit编码后的字节数组
输出:解码后的字符串信息
/**
* 7-bit解码
* 31D98C06
* @param data
* @return
*/
public static String decode7bit(byte[] d){
byte[] other_mask ={(byte) 0x80,(byte) 0xc0,(byte) 0xe0,(byte) 0xf0,(byte) 0xf8,(byte) 0xfc,(byte) 0xfe};
byte[] my_mask = {0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01};
byte other = 0;
byte temp = 0;
StringBuffer sb = new StringBuffer();
for(int i=0;i<d.length;i++){
int index = i%7;
temp = d[i];
//得到我的数据
d[i] = (byte) (d[i]&my_mask[index]);
d[i] = (byte) (d[i] << index);
if(index != 0){
d[i] = (byte) (d[i]&other_mask[7-index]);
other = (byte) (other>>(8-index));
other = (byte) (other&my_mask[7-index]);
d[i] = (byte) (d[i] | other);
}
//先把下一个数据信息拿走
other = (byte) (temp&other_mask[index]);
sb.append((char)d[i]);
if(index == 6){
other = (byte) (other>>1);
other = (byte) (other & 0x7f);
sb.append((char)other);
}
}
return sb.toString();
}