如何将字符串转换为十六进制 nodejs

新手上路,请多包涵

我一直在寻找一些标准函数,如十六进制到字符串但相反,我想将字符串转换为十六进制,但我只找到了这个 函数……

 // Example of convert hex to String
hex.toString('utf-8')

原文由 DarckBlezzer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
1 个回答

在 NodeJS 中,使用 Buffer 将字符串转换为十六进制。

 Buffer.from('hello world', 'utf8').toString('hex');

关于它如何工作的简单示例:

 const bufferText = Buffer.from('hello world', 'utf8'); // or Buffer.from('hello world')
console.log(bufferText); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>

const text = bufferText.toString('hex');
// To get hex
console.log(text); // 68656c6c6f20776f726c64

console.log(bufferText.toString()); // or toString('utf8')
// hello world

//one single line
Buffer.from('hello world').toString('hex')

原文由 Luis Estevez 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题