import java.io.UnsupportedEncodingException; /** * 编码类 * 功能:模拟PPP协议字节填充的编码过程 */ public class Code { // 把字符串的长度填充到8 private String fillEight(String str) { if (str.length() < 8) { str = "0" + str; str = fillEight(str); } return str; } // 返回数据部分二进制形式的字符串 private String getDataByte(byte[] b) { String str = ""; for (int temp : b) { temp &= 0xff; // 将高24位变成全0 str += fillEight(Integer.toBinaryString(temp)); } return str; } // 对字符串进行字节填充 private String fillByte(String str) { int count = 0; // 计算连续的1的个数 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '1') { count++; } else { count = 0; } if (count == 5) { str = str.substring(0,i + 1) + "0" + fillByte(str.substring(i + 1)); return str; } } return str; } // 对数据进行封装 private String packaging(String str) { if (str.length() > 1500) { str = packaging(str.substring(0,1500)) + packaging(str.substring(1500)); return str; } else { return "01111110" + str + "01111110"; } } // 返回编码后的字符串 public static String getCodedString(String str) throws UnsupportedEncodingException { return getCodedString(str.getBytes("UTF-8")); } // 返回编码后的字符串 public static String getCodedString(byte[] b) throws UnsupportedEncodingException { Code code = new Code(); return code.packaging(code.fillByte(code.getDataByte(b))); } }
import java.io.UnsupportedEncodingException; /** * 解码类 * 功能:模拟PPP协议字节填充的解码过程 */ public class Decode { // 返回数据部分二进制形式的字符串 private String getData(String str) { System.out.println(str.length()); String strBuffer = ""; int start = str.indexOf("01111110") + 8; int end = str.indexOf("01111110",start); System.out.println(start + " " + end); if (start >= end) { return ""; } strBuffer = str.substring(start,end); if (end + 8 < str.length()) { strBuffer += getData(str.substring(end + 8)); } System.out.println(strBuffer.length()); return strBuffer; } // 抽出字符串的填充字节 private String removeByte(String str) { int count = 0; // 计算连续的1的个数 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '1') { count++; } else { count = 0; } if (count == 5) { str = str.substring(0,i + 1) + removeByte(str.substring(i + 2)); return str; } } return str; } // 返回数据的byte型数组 private byte[] getBytes(String str) { int length = str.length() / 8,temp; byte b[] = new byte[length]; for (int i = 0; i < length; i++) { temp = Integer.parseInt(str.substring(8 * i,8 * (i + 1)),2); b[i] = (byte) temp; } return b; } // 返回解码后的字符串 public static String getString(String str) throws UnsupportedEncodingException { Decode decode = new Decode(); return getString(decode .getBytes(decode.removeByte(decode.getData(str)))); } // 返回解码后的字符串 public static String getString(byte[] b) throws UnsupportedEncodingException { return new String(b,"UTF-8"); } }