如何在JavaScript/Java中创建解析TLV并完成Base64编码,附TLV规则说明
TLV编解码及Base64处理实现方案
本次实现严格遵循你指定的TLV规则:
- Tag:占1字节,取值匹配业务定义的Tag映射表
- Length:占1字节,值为对应Value字段经UTF8编码后的字节数组长度
- Value:可变长度,为字段值经UTF8编码生成的字节数组
JavaScript 实现
1. TLV创建 + Base64编码
// 入参为对象数组,每个对象包含tag(数字,取值范围0-255)、value(字符串) function buildTlvAndEncodeBase64(tlvItems) { let totalLength = 0; const itemByteList = []; for (const item of tlvItems) { const valueBytes = new TextEncoder().encode(item.value); const len = valueBytes.length; // 校验长度不超过1字节最大值255 if (len > 255) throw new Error(`Value长度超出1字节限制,Tag: ${item.tag}`); totalLength += 2 + len; itemByteList.push({ tag: item.tag, len, valueBytes }); } // 组装TLV字节数组 const tlvBuffer = new Uint8Array(totalLength); let offset = 0; for (const item of itemByteList) { tlvBuffer[offset++] = item.tag; tlvBuffer[offset++] = item.len; tlvBuffer.set(item.valueBytes, offset); offset += item.len; } // 转Base64,同时兼容浏览器和Node.js环境 if (typeof Buffer !== 'undefined') { return Buffer.from(tlvBuffer).toString('base64'); } else { return btoa(String.fromCharCode.apply(null, tlvBuffer)); } }
2. TLV解析(支持Base64格式输入)
function parseTlvFromBase64(base64Str) { // 先将Base64转换为Uint8Array字节数组 let tlvBuffer; if (typeof Buffer !== 'undefined') { tlvBuffer = new Uint8Array(Buffer.from(base64Str, 'base64')); } else { const binaryStr = atob(base64Str); tlvBuffer = new Uint8Array(binaryStr.length); for (let i = 0; i < binaryStr.length; i++) { tlvBuffer[i] = binaryStr.charCodeAt(i); } } // 解析TLV结构 const result = []; let offset = 0; while (offset < tlvBuffer.length) { const tag = tlvBuffer[offset++]; const len = tlvBuffer[offset++]; const valueBytes = tlvBuffer.slice(offset, offset + len); const value = new TextDecoder().decode(valueBytes); result.push({ tag, value }); offset += len; } return result; }
使用示例
// 示例:Tag 0x01对应字段值"测试内容",Tag 0x02对应字段值"123456" const items = [{tag: 0x01, value: "测试内容"}, {tag: 0x02, value: "123456"}]; const base64 = buildTlvAndEncodeBase64(items); console.log("TLV编码后Base64:", base64); const parsed = parseTlvFromBase64(base64); console.log("解析结果:", parsed);
Java 实现
依赖说明
JDK 8及以上版本即可使用,不需要引入第三方依赖,直接使用JDK内置的java.util.Base64和java.nio.charset.StandardCharsets。
1. TLV实体类(可选,方便参数传递)
public class TlvItem { private int tag; // 取值范围0-255 private String value; public TlvItem(int tag, String value) { this.tag = tag; this.value = value; } // 此处可自行补充getter、setter方法 public int getTag() { return tag; } public String getValue() { return value; } }
2. TLV创建 + Base64编码
import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.List; public class TlvEncoder { public static String buildTlvAndEncodeBase64(List<TlvItem> tlvItems) { // 计算TLV总字节长度 int totalLen = 0; for (TlvItem item : tlvItems) { byte[] valueBytes = item.getValue().getBytes(StandardCharsets.UTF_8); if (valueBytes.length > 255) { throw new IllegalArgumentException("Value长度超出1字节限制,Tag:" + item.getTag()); } totalLen += 2 + valueBytes.length; } // 组装TLV字节数组 byte[] tlvBytes = new byte[totalLen]; int offset = 0; for (TlvItem item : tlvItems) { byte[] valueBytes = item.getValue().getBytes(StandardCharsets.UTF_8); tlvBytes[offset++] = (byte) item.getTag(); tlvBytes[offset++] = (byte) valueBytes.length; System.arraycopy(valueBytes, 0, tlvBytes, offset, valueBytes.length); offset += valueBytes.length; } // 转换为Base64格式输出 return Base64.getEncoder().encodeToString(tlvBytes); } }
3. TLV解析(支持Base64格式输入)
import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.List; public class TlvDecoder { public static List<TlvItem> parseTlvFromBase64(String base64Str) { byte[] tlvBytes = Base64.getDecoder().decode(base64Str); List<TlvItem> result = new ArrayList<>(); int offset = 0; while (offset < tlvBytes.length) { int tag = tlvBytes[offset++] & 0xFF; // 转换为无符号字节 int len = tlvBytes[offset++] & 0xFF; byte[] valueBytes = new byte[len]; System.arraycopy(tlvBytes, offset, valueBytes, 0, len); String value = new String(valueBytes, StandardCharsets.UTF_8); result.add(new TlvItem(tag, value)); offset += len; } return result; } }
使用示例
import java.util.Arrays; import java.util.List; public class TlvTest { public static void main(String[] args) { List<TlvItem> items = Arrays.asList( new TlvItem(0x01, "测试内容"), new TlvItem(0x02, "123456") ); String base64 = TlvEncoder.buildTlvAndEncodeBase64(items); System.out.println("TLV编码后Base64:" + base64); List<TlvItem> parsed = TlvDecoder.parseTlvFromBase64(base64); parsed.forEach(item -> System.out.printf("Tag: %02X, Value: %s%n", item.getTag(), item.getValue())); } }
注:代码中Tag字段的具体取值可直接替换为你业务映射表中对应的数值即可正常使用。
内容的提问来源于stack exchange,提问作者Mahmoud Aheed
相关产品推荐
相关产品推荐

