有项目使用到了TLV组解包的模式,特意在此记录,以供参考:
/**
* 将字符串转换为TLV对象
* Created by ZFR on 2019/5/29.
*/
public class TlvUtils {
/**
* 将16进制字符串转换为TLV对象列表
*
* @param hexString
* @return
*/
public static List<TLV2> builderTlvList(String hexString) {
List<TLV2> tlvs = new ArrayList<TLV2>();
int position = 0;
while (position != StringUtils.length(hexString)) {
String _hexTag = getTag(hexString, position);
Log.d("zfr-_hexTag:===", _hexTag);
position += _hexTag.length();
LPositon l_position = getLengthAndPosition(hexString, position);
int _vl = l_position.get_vL();
position = l_position.get_position();
String _value = StringUtils.substring(hexString, position, position + _vl * 2);
position = position + _value.length();
tlvs.add(new TLV2(_hexTag, _vl, _value));
}
return tlvs;
}
/**
* 将16进制字符串转换为TLV对象MAP
*
* @param hexString
* @return
*/
public static Map<String, TLV2> builderTlvMap(String hexString) {
Map<String, TLV2> tlvs = new HashMap<String, TLV2>();
int position = 0;
while (position != hexString.length()) {
String _hexTag = getTag(hexString, position);
position += _hexTag.length();
LPositon l_position = getLengthAndPosition(hexString, position);
int _vl = l_position.get_vL();
position = l_position.get_position();
String _value = hexString.substring(position, position + _vl * 2);
position = position + _value.length();
tlvs.put(_hexTag, new TLV2(_hexTag, _vl, _value));
}
return tlvs;
}
/**
* 返回最后的Value的长度
*
* @param hexString
* @param position
* @return
*/
private static LPositon getLengthAndPosition(String hexString, int position) {
String firstByteString = hexString.substring(position, position + 4);
Log.d("zfr-firstByteString====", firstByteString);
return new LPositon(Integer.parseInt(zfrUtils.toStringHex(firstByteString)), position + 4);
/*int i = Integer.parseInt(firstByteString, 16);
String hexLength = "";
if (((i >>> 7) & 1) == 0) {
hexLength = hexString.substring(position, position + 2);
position = position + 2;
} else {
// 当最左侧的bit位为1的时候,取得后7bit的值,
int _L_Len = i & 127;
position = position + 2;
hexLength = hexString.substring(position, position + _L_Len * 2);
// position表示第一个字节,后面的表示有多少个字节来表示后面的Value值
position = position + _L_Len * 2;
}
return new LPositon(Integer.parseInt(hexLength, 16), position);*/
}
/**
* 取得子域Tag标签
*
* @param hexString
* @param position
* @return
*/
private static String getTag(String hexString, int position) {
String firstByte = StringUtils.substring(hexString, position, position + 4);
Log.d("zfr-firstByte:==", firstByte);
return hexString.substring(position, position + 4);
/*int i = Integer.parseInt(firstByte, 16);
Log.d("zfr-i:==",i+"");
if ((i & 0x1f) == 0x1f) {
Log.d("zfr-2字节:=====","0000000000");
return hexString.substring(position, position + 4);
} else {
Log.d("zfr-1字节:=====","0000000000");
return hexString.substring(position, position + 2);
}*/
}
}
注:如有问题可以回复,看到第一时间分析解决,码农不易,感觉对您有用,帮助到您,可否打赏一杯可乐,在此谢过诸位,愿诸君终成大神,前程似锦~~~