Has*_*aan 10 string encoding buffer node.js
我需要使用 nodejs 8 将数据转换为字符串到十六进制,然后再从十六进制转换为字符串
我在从十六进制解码为字符串时遇到问题
要转换的代码 string into hex
function stringToHex(str)
{
const buf = Buffer.from(str, 'utf8');
return buf.toString('hex');
}
Run Code Online (Sandbox Code Playgroud)
要转换的代码 hex into string
function hexToString(str)
{
const buf = new Buffer(str, 'hex');
return buf.toString('utf8');
}
Run Code Online (Sandbox Code Playgroud)
我有字符串 dailyfile.host
编码输出:3162316637526b62784a5a37697a45796c656d465643747a4a505a6f59774641534c75714733544b4446553d
解码输出:1b1f7RkbxJZ7izEylemFVCtzJPZoYwFASLuqG3TKDFU=
解码所需的输出:dailyfile.host
Pat*_*rts 16
您还需要Buffer.from()用于解码。考虑编写一个高阶函数来减少重复代码的数量:
const convert = (from, to) => str => Buffer.from(str, from).toString(to)
const utf8ToHex = convert('utf8', 'hex')
const hexToUtf8 = convert('hex', 'utf8')
hexToUtf8(utf8ToHex('dailyfile.host')) === 'dailyfile.host'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17723 次 |
| 最近记录: |