16进制字符串转字符串

一、浏览器上

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 库:

npm install iconv-lite

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

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 换行,要 标签才能进行换行

<text class="result_content"> 
				{{logChina}}
			</text>
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值