可以使用 Node.js 内置的 Buffer 对象来实现将字符串转换为十六进制。

以下是一个示例代码:

const str = 'hello world';
const hex = Buffer.from(str, 'utf8').toString('hex');
console.log(hex);

解释:

  • Buffer.from(str, 'utf8') 创建一个 Buffer 对象,将字符串编码为 UTF-8 格式的字节序列。
  • toString('hex') 将 Buffer 对象转换为十六进制字符串。

输出:

68656c6c6f20776f726c64

在上面的示例中,我们将字符串'hello world' 转换为十六进制字符串'68656c6c6f20776f726c64'。

Node.js 字符串转十六进制:简单实现指南

原文地址: https://www.cveoy.top/t/topic/nYUt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录