js 字符串与16进制互转代码
时间: 2023-08-09 09:05:39 浏览: 84
字符串与16进制数据互转
将字符串转成16进制:
```javascript
function stringToHex(str) {
let hex = "";
for(let i=0; i<str.length; i++) {
let charCode = str.charCodeAt(i).toString(16);
hex += charCode.length < 2 ? "0" + charCode : charCode;
}
return hex;
}
```
将16进制转成字符串:
```javascript
function hexToString(hex) {
let str = "";
for(let i=0; i<hex.length; i+=2) {
let charCode = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(charCode);
}
return str;
}
```
使用示例:
```javascript
let str = "hello world";
let hex = stringToHex(str);
console.log(hex); // 68656c6c6f20776f726c64
console.log(hexToString(hex)); // hello world
```
阅读全文