
前言Hex十六进制编码将二进制数据转换为十六进制字符串常用于加密结果展示、数据调试等场景。pura/harmony-utils的EncryptUtil封装了Hex编解码方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解帮助开发者快速掌握并应用到实际项目中。一、Hex编解码核心APIEncryptUtil提供了以下Hex编解码方法方法说明返回类型使用场景encodeHex(data)编码为Hex字符串string数据展示decodeHex(hex)从Hex字符串解码Uint8Array数据还原1.1 核心特性简洁易用封装复杂逻辑为一行调用降低使用门槛类型安全完整的TypeScript类型定义编译期即可发现错误异常处理内置异常捕获机制避免运行时崩溃双向转换支持二进制数据与Hex字符串互转1.2 Hex编码对照原始数据Hex编码说明Hello48656C6C6FASCII文本0x01 0xFF01FF二进制数据[0, 255]00FF字节数组二、完整使用步骤2.1 安装依赖ohpminstallpura/harmony-utils2.2 Hex编码import{EncryptUtil}frompura/harmony-utils;Button(Hex编码).width(100%).onClick((){try{letdatanewUint8Array([0x48,0x65,0x6C,0x6C,0x6F]);lethexEncryptUtil.encodeHex(data);this.result数据: Hello\nHex:${hex};}catch(e){this.result异常: e;}})2.3 Hex解码Button(Hex解码).width(100%).onClick((){try{lethex48656C6C6F;letdataEncryptUtil.decodeHex(hex);lettextString.fromCharCode(...data);this.resultHex:${hex}\n解码:${text};}catch(e){this.result异常: e;}})三、完整页面示例import{EncryptUtil}frompura/harmony-utils;EntryComponentstruct HexDemo{Stateresult:string;build(){Column({space:12}){Button(Hex编码).width(100%).onClick((){letdatanewUint8Array([0x48,0x65,0x6C,0x6C,0x6F]);this.resultEncryptUtil.encodeHex(data);});Button(Hex解码).width(100%).onClick((){letdataEncryptUtil.decodeHex(48656C6C6F);this.resultString.fromCharCode(...data);});Text(this.result).fontSize(14).fontColor(#333333)}.padding(16)}}四、进阶用法4.1 加密结果展示import{EncryptUtil}frompura/harmony-utils;asyncfunctionshowHashResult(input:string):Promisestring{lethashawaitEncryptUtil.sha256(input);returnEncryptUtil.encodeHex(hash);}4.2 数据调试functiondebugBinaryData(data:Uint8Array):string{returnEncryptUtil.encodeHex(data);}五、注意事项大小写Hex编码通常输出小写字母长度倍增每个字节编码为2个Hex字符奇数长度解码时奇数长度Hex字符串可能报错初始化依赖使用前需确保AppUtil.init()已调用非Hex字符解码时包含非Hex字符会报错六、常见问题Q1: Hex编码输出大写还是小写通常输出小写如需大写可使用toUpperCase()转换。Q2: 解码时Hex字符串长度必须是偶数吗是的每个字节对应2个Hex字符奇数长度无法正确解码。Q3: Hex编码是加密吗不是Hex只是编码方式任何人都可以解码。Q4: 如何将字符串转为Hex先将字符串转为Uint8Array再调用encodeHex。总结EncryptUtil的Hex编解码方法为二进制数据展示提供了便捷支持。本文详细介绍了核心API、使用步骤、完整示例、进阶用法以及常见问题的解决方案。开发者可以利用这些方法展示加密结果、调试二进制数据。本文基于pura/harmony-utils工具库更多功能请参考官方文档与后续系列文章。