16进制字符串转字符串

一、浏览器上

c 复制代码
function hexToUtf8(hexString) {
  const hexArray = hexString.match(/.{1,2}/g) || [];
  const uint8Array = new Uint8Array(hexArray.map(hex => parseInt(hex, 16)));

  const textDecoder = new TextDecoder('GB2312'); //可以切换字符编码
  return textDecoder.decode(uint8Array);
}

// 示例用法
const hexString = "0D0A2D2D2D20B6C1C8A1B6A8CAB1C9CFB1A8B2CECAFD202D2D2D0D0A"; // 16进制字符串
const result = hexToUtf8(hexString);
console.log(result); // 输出: "hello, 你好"

在微信小程序中提示 TextDecoder is not defined,微信小程序环境中可能没有内置的TextDecoder

二、微信小程序上

在微信小程序中,如果你需要指定编码格式为GB2312,可以使用一个库来进行解码,因为微信小程序环境并没有原生支持GB2312编码。你可以考虑使用一个名为 iconv-lite 的库,该库支持多种字符编码的转换。

1、首先,在你的小程序项目中安装 iconv-lite 库:

c 复制代码
npm install iconv-lite

2、然后,使用以下代码进行解码:

c 复制代码
const iconv = require('iconv-lite');

function hexToGb2312(hexString) {
  const buffer = Buffer.from(hexString, 'hex');
  const decodedString = iconv.decode(buffer, 'GB2312');
  return decodedString;
}

// 示例用法
const hexString = "0D0A2D2D2D20B6C1C8A1B6A8CAB1C9CFB1A8B2CECAFD202D2D2D0D0A"; // 16进制字符串
const result = hexToGb2312(hexString);
console.log(result); // 输出: "hello, 你好"

3、然在再在页面中显示

由于字符串中有\r\n,标签并不能使\r\n 换行,要 标签才能进行换行

c 复制代码
<text class="result_content"> 
				{{logChina}}
			</text>
相关推荐
咖啡の猫2 天前
微信小程序页面配置
微信小程序·小程序·notepad++
咖啡の猫2 天前
微信小程序WXML 模板语法
微信小程序·小程序·notepad++
花卷HJ4 天前
【微信小程序】open-type=“contact“ 客服按钮样式无法设置?隐藏 button + label 触发完美解决
微信小程序·小程序·notepad++
難釋懷7 天前
微信小程序案例 - 自定义 tabBar
微信小程序·小程序·notepad++
百锦再10 天前
AI视频生成模型从无到有:构建、实现与调试完全指南
人工智能·python·ai·小程序·aigc·音视频·notepad++
FreeBuf_11 天前
黑猫黑客组织通过伪造Notepad++网站传播窃密恶意软件
notepad++
UpYoung!12 天前
【免费开源文本编辑器】轻量级文本编辑器——Notepad++ 下载安装教程
文本编辑器·notepad++·实用工具·开源工具·运维必备·办公学习必备
点PY14 天前
Notepad++离线安装HexEditor
notepad++
GHL28427109014 天前
Notepad++多行编辑技巧:批量删除
notepad++
微风中的麦穗16 天前
【开源文本编辑器】轻量级免费文本编辑器——Notepad++ 完全指南:专业选择做专业的事
notepad++