码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2020-03-25 10:47:05      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:count   app   androi   字符   合并   16进制   test   数据   length   

 /**

 * 十六进制转字节数组
 * @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;
}

 

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

标签:count   app   androi   字符   合并   16进制   test   数据   length   

原文地址:https://www.cnblogs.com/dmrbell/p/12564304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!