package com.ld.igds.protocol.utl; import java.text.ParseException; /** * GPS工具类 */ public class GpsUtils { /** * 标识位 */ public static final String MSG = "7E"; /** * 注册消息ID */ public static final String MSG_01 = "0100"; /** * 注册应答消息ID */ public static final String MSG_11 = "8100"; /** * 鉴权消息ID */ public static final String MSG_02 = "0102"; /** * 鉴权应答消息ID */ public static final String MSG_22 = "8001"; /** * 位置信息主动汇报消息ID */ public static final String MSG_333 = "0200"; /** * 位置信息查询应答消息ID */ public static final String MSG_03 = "0201"; /** * 位置信息查询消息ID */ public static final String MSG_33 = "8201"; /** * 添加标识符 * @param msg * @return */ public static String addIdentifier(String msg){ return MSG+msg+MSG; } /** * 去除标识符 * @param msg * @return */ public static String delIdentifier(String msg){ return msg.replaceAll(MSG,""); } /** * 转义:0x7D-->0x7D0x01,0x7E-->0x7D0x02 * @param msg * @return */ public static String escapeCode1(String msg){ String str = ""; for(int i=0;i<=msg.length()-2;i=i+2){ str += "0x" + msg.substring(i,i+2); } String s = str.replaceAll("0x7D", "0x7D0x01"); return s.replaceAll("0x7E", "0x7D0x02").replaceAll("0x", ""); } /** * 转义:0x7D0x02-->0x7E,0x7D0x01-->0x7D * @param msg * @return */ public static String escapeCode2(String msg){ String str = ""; for(int i=0;i<=msg.length()-2;i=i+2){ str += "0x" + msg.substring(i,i+2); } String s = str.replaceAll("0x7D0x02", "0x7E"); return s.replaceAll("0x7D0x01", "0x7D").replaceAll("0x", ""); } public static void main(String[] args) throws ParseException { String msg = "01 02 00 06 01 38 20 03 63 16 00 01 01 38 20 03 63 16"; String checkCode = checkCode(msg.replaceAll(" ","")); System.out.println(checkCode); } /** * BCC校验(异或校验) * @param content * @return */ public static String checkCode(String content) { String con = change(content); String[] b = con.split(" "); int a = 0; for (int i = 0; i < b.length; i++) { a = a ^ Integer.parseInt(b[i], 16); } if(a<10){ StringBuffer sb = new StringBuffer(); sb.append("0"); sb.append(a); return sb.toString(); } return Integer.toHexString(a); } private static String change(String content) { String str = ""; for (int i = 0; i < content.length(); i++) { if (i % 2 == 0) { str += " " + content.substring(i, i + 1); } else { str += content.substring(i, i + 1); } } return str.trim(); } }