我需要使用nodejs 8将数据转换为String到Hex,然后再次从Hex转换为String
从十六进制解码为字符串时遇到问题
要转换的代码string into hex
function stringToHex(str)
{
const buf = Buffer.from(str, 'utf8');
return buf.toString('hex');
}
要转换的代码hex into string
function hexToString(str)
{
const buf = new Buffer(str, 'hex');
return buf.toString('utf8');
}
我有字符串dailyfile.host
编码的输出:3162316637526b62784a5a37697a45796c656d465643747a4a505a6f59774641534c75714733544b4446553d
解码的输出:1b1f7RkbxJZ7izEylemFVCtzJPZoYwFASLuqG3TKDFU=
必填输出:dailyfile.host
答案 0 :(得分:2)
您还需要使用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'