Android 处理蓝牙(例如字节数组)数据的方法,例如十六进制转字节数组

 /**

 * 十六进制转字节数组
 * @param hexString
 * @return
 */
public static byte[] hexStringToBytes(String hexString) {
    if (hexString == null || hexString.equals(“”)) {
        return null;
    }
    hexString = hexString.toUpperCase();
    int length = hexString.length() / 2;
    char[] hexChars = hexString.toCharArray();
    byte[] d = new byte[length];
    for (int i = 0; i < length; i++) {
        int pos = i * 2;
        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
    }
    return d;
}

 

/**
 * 字节数组转16进制
 * @param bytes 需要转换的byte数组
 * @return  转换后的Hex字符串
 */
public static String bytesToHex(byte[] bytes) {
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(bytes[i] & 0xFF);
        if(hex.length() < 2){
            sb.append(0);
        }
        sb.append(hex);
    }
    return sb.toString();
}

 

  /**
 * byte转int类型
 * 如果byte是负数,则转出的int型是正数
 * @param b
 * @return
 */
public static int byteToInt(byte b){
   System.out.println(“byte 是:”+b);
   int x = b & 0xff;
   System.out.println(“int 是:”+x);
   return x;
}

 

/**
 * 字节转十六进制
 * @param b 需要进行转换的byte字节
 * @return  转换后的Hex字符串
 */
public static String byteToHex(byte b){
    String hex = Integer.toHexString(b & 0xFF);
    if(hex.length() < 2){
        hex = “0” + hex;
    }
    return hex;
}

 

/**
 * 合并多个byte[]为一个byte数组
 * @param values
 * @return
 */
public static byte[] byteMergerAll(byte[]… values) {
    int length_byte = 0;
    for (int i = 0; i < values.length; i++) {
        length_byte += values[i].length;
    }
    byte[] all_byte = new byte[length_byte];
    int countLength = 0;
    for (int i = 0; i < values.length; i++) {
        byte[] b = values[i];
        System.arraycopy(b, 0, all_byte, countLength, b.length);
        countLength += b.length;
    }
    return all_byte;
}