package com.zteits.nbiot.decoder; import java.util.Arrays; public class Utilty { private static Utilty instance = new Utilty(); public static Utilty getInstance() { return instance; } public static final int MIN_MID_VALUE = 1; public static final int MAX_MID_VALUE = 65535; public static int bytes2Int(byte[] b, int start, int length) { int sum = 0; int end = start + length; for (int k = start; k < end; k++) { int n = ((int) b[k]) & 0xff; n <<= (--length) * 8; sum += n; } return sum; } public static byte[] int2Bytes(int value, int length) { byte[] b = new byte[length]; for (int k = 0; k < length; k++) { b[length - k - 1] = (byte) ((value >> 8 * k) & 0xff); } return b; } public boolean isValidofMid(int mId) { if (mId < MIN_MID_VALUE || mId > MAX_MID_VALUE) { return false; } return true; } public static String parseByte2HexStr(byte[] buf) { if (null == buf) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 16进制转换成为integer * @return */ public static Integer hexStringToInteger(byte[] original, int from, int to) { String s = Utilty.parseByte2HexStr(Arrays.copyOfRange(original, from, to)); return Integer.parseInt(s,16); } /** * 16进制转换成为string类型字符串 * @return */ public static String hexStringToString(byte[] original, int from, int to) { String s = Utilty.parseByte2HexStr(Arrays.copyOfRange(original, from, to)); if (s == null || s.equals("")) { return null; } s = s.replace(" ", ""); byte[] baKeyword = new byte[s.length() / 2]; for (int i = 0; i < baKeyword.length; i++) { try { baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); } catch (Exception e) { e.printStackTrace(); } } try { s = new String(baKeyword, "UTF-8"); new String(); } catch (Exception e1) { e1.printStackTrace(); } return s; } }