一、方法:
/**
* 字節數組轉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));
個人總結,歡迎指導!