js hex 转utf8
时间: 2023-08-18 16:04:01 浏览: 60
在 JavaScript 中,可以使用 `TextDecoder` 对象将十六进制字符串转换为 UTF-8 编码的字符串。具体步骤如下:
1. 将十六进制字符串转换为 `Uint8Array` 类型的数组
```javascript
const hexString = 'e4bda0e5a5bd'; // 十六进制字符串
const uint8Array = new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); // 转换为 Uint8Array 类型的数组
```
2. 将 `Uint8Array` 类型的数组转换为 UTF-8 编码的字符串
```javascript
const utf8String = new TextDecoder('utf-8').decode(uint8Array); // 转换为 UTF-8 编码的字符串
console.log(utf8String); // 输出:你好
```
现在,你就可以将十六进制字符串转换为 UTF-8 编码的字符串了。如果你需要将其他编码的字符串转换为普通的字符串,可以将 `utf-8` 替换为相应的编码名称。
相关问题
vue3 hex 转utf8
在 Vue 3 中,可以使用 `TextDecoder` 对象将十六进制字符串转换为 UTF-8 编码的字符串。具体步骤如下:
1. 将十六进制字符串转换为 `Uint8Array` 类型的数组
```javascript
const hexString = 'e4bda0e5a5bd'; // 十六进制字符串
const uint8Array = new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); // 转换为 Uint8Array 类型的数组
```
2. 将 `Uint8Array` 类型的数组转换为 UTF-8 编码的字符串
```javascript
const utf8String = new TextDecoder('utf-8').decode(uint8Array); // 转换为 UTF-8 编码的字符串
console.log(utf8String); // 输出:你好
```
现在,你就可以将十六进制字符串转换为 UTF-8 编码的字符串了。如果你需要将其他编码的字符串转换为普通的字符串,可以将 `utf-8` 替换为相应的编码名称。
vue3 hex转utf8 不使用TextDecoder
在 Vue 3 中,你也可以不使用 `TextDecoder` 对象将十六进制字符串转换为 UTF-8 编码的字符串,而是使用 JavaScript 的 `String.fromCharCode` 方法将每个十六进制字符转换为对应的 Unicode 码点,然后使用 `String` 对象的 `fromCharCode` 方法将 Unicode 码点转换为字符,最后拼接成字符串。具体步骤如下:
```javascript
const hexString = 'e4bda0e5a5bd'; // 十六进制字符串
let utf8String = '';
for (let i = 0; i < hexString.length; i += 2) {
const codePoint = parseInt(hexString.substr(i, 2), 16); // 将每个十六进制字符转换为对应的 Unicode 码点
utf8String += String.fromCharCode(codePoint); // 将 Unicode 码点转换为字符
}
console.log(utf8String); // 输出:你好
```
注意,这种方法只适用于将十六进制字符串转换为 UTF-8 编码的字符串。如果你需要将其他编码的字符串转换为普通的字符串,可以使用相应编码的解码方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)