一、方法:
/**
* 字节数组转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();
}
/**
* 十六进制转字节数组
* @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;
}
/**
* 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;
}
二、处理蓝牙字节数组案例
心电信号模拟量通知:100ms通知一次,每次53个有效数据,第二个字节为帧序号,第三个字节为电量,第四个字节为设备状态,后面每个有效数据两个字节,固定长度55字节(一帧长度55,分3次发过来,长度分别是20、20、15)。
1、每3条数据合并成一条字节数组
List<String> idata = new ArrayList<>();
String dtr = "";
if (data[0] == -34) { //每3条数据放到集合idata中
for (int i = 0; i < idata.size(); i++) {
dtr = dtr + idata.get(i);
}
setElectdiogramValue(dtr); //通过监听器传到显示activity或fragment,一帧一帧传过去,每传一帧清一次idata集合和初始化一次dtr
dtr = "";
idata.clear();
idata.add(ZHexUtil.bytesToHex(data));
} else {
idata.add(ZHexUtil.bytesToHex(data));
}
2、负数十进制转16进制
前提:已知十六进制,转十进制
byte[] bt = new byte[]{ (byte) 0xDE,(byte) 0xFE,(byte) 0x16,(byte) 0x00,(byte) 0x68,(byte) 0xA1,(byte) 0xA3,(byte) 0xA9};
Log.i(TAG, "心电图数据:DE、FE、16、00、68、A1、A3、A9进制转换:" + Arrays.toString(bt));
个人总结,欢迎指导!