我的方法parseTLV()
有时不能正确地归结为构造值(子 TLV)。我使用过滤器((tag & 0x20)! = 0)
来检测构造值,但有时它不能按预期工作。
例如
70178C159F02069F03069F1A0295055F2A029A039C019F3704
导致以下结果parseTLV
:
- 标签:
70
- 值:8C159F02069F03069F1A0295055F2A029A039C019F3704
- 标签:
8C
- 值:9F02069F03069F1A0295055F2A029A039C019F3704
但是,我希望得到
- 标签:
70
- 值:8C159F02069F03069F1A0295055F2A029A039C019F3704
- 标签:
8C
- 值:9F02069F03069F1A0295055F2A029A039C019F3704
- 标签:
9F02
- 值:06
- 标签:
9F03
- 值:06
- 标签:
9F1A
- 值:02
- 标签:
95
- 值:05
- 标签:
5F2A
- 值:02
- 标签:
9A
- 值:03
- 标签:
9C
- 值:01
- 标签:
9F37
- 值:04
- 标签:
private ITlv.ITlvDataObjList parseTLV(byte[] src) {
try {
if (isBytesEmpty(src)) {
return null;
}
_tlvList = _tlv.createTlvDataObjectList();
int start = 0;
int end = start + src.length;
while (start < end) {
// tag has 1 byte (0xFF)
int tag = src[start++] & 0xFF;
//
if (tag == 0x00 || tag == 0xFF) {
continue;
}
// tag has more bytes?
if ((tag & 0x1F) == 0x1F) {
if (start >= src.length) {
break;
}
// tag has 2 bytes (0xFFFF)
tag = (tag << 8) | src[start++] & 0xFF;
// tag has 3 bytes (0xFFFFFF)
if ((tag & 0x80) != 0) {
if (start >= src.length) {
break;
}
tag = (tag << 8) | src[start++] & 0xFF;
}
// break when tag > 3 bytes
if ((tag & 0x80) != 0) {
continue;
}
}
// length 1 byte (0x7F)
int length = src[start++] & 0xFF;
// length has more bytes?
if (length >= 0x80) {
// break when length > 2 bytes
int count = length & 0x7F;
if (count > 3) {
continue;
}
// length 1 bytes (0x80-0xFF) or 2 bytes (0x100-0xFFFF)
length = 0;
for (int k = 0; k < count; k++) {
if (start >= src.length) {
break;
}
length = (length << 8) | src[start++] & 0xFF;
}
}
// values
byte[] value = new byte[length];
System.arraycopy(src, start, value, 0, length);
//
// create tlv object
ITlv.ITlvDataObj tlvObj = _tlv.createTlvDataObject();
tlvObj.setTag(tag);
tlvObj.setValue(value);
// save tlv object to list
_tlvList.addDataObj(tlvObj);
//
// next tag
while (tag > 0xFF) {
tag = tag >> 8;
}
// is constructed (has child)?
if ((tag & 0x20) != 0) {
continue;
}
start = start + value.length;
}
return _tlvList;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}