說明
- hexString是字節序是小端的(讀值得時候會轉爲大端來讀取值)
- valueByteSizes是個根據要求順序讀取值得字節大小的數組。
例如:new byte[]{4,2,1},程序會順序讀取hexString字符串:
- 第一個值取4個字節並讀取其值,
- 第2個值取2個字節,
- 第3個值取1個字節,
4.(如果存在)第4個值取1個字節。
其傳的字節數組不足以讀取完全部的16進制字符串,將取字節數組的最後一個元素作爲讀取字節的大小。
public void handle(String hexString, byte[] valueByteSizes){
// 1個Byte標識2個十六進制的字符
final byte HexByte = 2;
// 小端序和大端序讀取區
final ByteBuffer writeByteBufferLittleEndian = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
final ByteBuffer readByteBufferBigEndian = writeByteBufferLittleEndian.asReadOnlyBuffer().order(ByteOrder.BIG_ENDIAN);;
final byte valueByteLength = (byte) valueByteSizes.length;
// 數據字符串的長度
int hexLength = hexString.length();
// 讀取指針的位置,下一個的位置
int position = 0;
// 計次索引,注意,這是個索引值,從0開始
int itemIndex = 0;
// 初始字節
int valueByteSize = valueByteSizes[0];
while (position < hexLength) {
// 計算當前position + (十六進制的位數長度),代表當前值的結束位置
// position ~ posEnd,左閉右開,代表當前取16進制的字符串區間。
int posEnd = position + (byte) (valueByteSize * HexByte);
// 元素數據,需要額外的處理
String rawHexString = hexString.substring(position, posEnd);
long rawValue = Long.parseLong(rawHexString, 16);
// 經過處理轉換的最終數據的值
long value;
// 如果是單字節,就不需要小端寫入->大端讀取
if(valueByteSize == 1){
value = rawValue;
}else{
writeByteBufferLittleEndian.putLong(rawValue);
// 根據字節大小進行不同的調用
switch (valueByteSize) {
case 1:
value = readByteBufferBigEndian.get();
break;
case 2:
value = readByteBufferBigEndian.getShort();
break;
case 4:
value = readByteBufferBigEndian.getInt();
break;
case 8:
value = readByteBufferBigEndian.getLong();
break;
default:
throw new RuntimeException("不支持此字節操作");
}
}
// System.out.printf("處理數據項 %s,%s == %s -> %s ==> %s \n", position, posEnd, rawHexString, rawValue, value);
// 返回的是下一個值所要讀取的字節數
doHandle(value, itemIndex++);
/*
更新下一個值所代表的字節數,
當 valueByteLength < itemIndex 時,保留最後一次的字節數用於提取剩下的值
*/
if(itemIndex < valueByteLength) {
valueByteSize = valueByteSizes[itemIndex];
}
// 更新當前開始位置的指針
position = posEnd;
writeByteBufferLittleEndian.clear();
readByteBufferBigEndian.clear();
}
}
附加
1. base64轉爲16進制字符串(主要代碼)
byte[] decodeValue = Base64.getDecoder().decode(value);
hexBinaryString = DatatypeConverter.printHexBinary(decodeValue);