如何在Node.js中将字符串转换为十六进制

20

我正在寻找一些标准的函数,如将十六进制转换为字符串,但需要相反的功能,我想要将字符串转换为十六进制,但我只找到了这个函数...

// Example of convert hex to String
hex.toString('utf-8')
4个回答

55

在 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')

我有一个包含冒号的base64字符串,当我将其转换为十六进制再转回base64时,它会去掉冒号。感谢您的解决方法! - droid-zilla
3
这个在react-native中可行,只需要安装 yarn add buffer - kemicofa ghost
想要输出间距均匀的两个字母,只需要执行以下操作:Buffer.from('hello world', 'utf8').toString('hex').replace(/../g, '$& ') - Ke Vin

8
您可以使用以下类似的函数:

您可以使用以下类似的函数:

  function stringToHex(str) {

  //converting string into buffer
   let bufStr = Buffer.from(str, 'utf8');

  //with buffer, you can convert it into hex with following code
   return bufStr.toString('hex');

   }

 stringToHex('some string here'); 

2

NPM amrhextotext,是一个简单的文本和十六进制之间的转换器。

安装


npm i amrhextotext

用法:

const text = 'test text'
const hex = '746573742074657874'

const convert = require('amrhextotext')

//convert text to hex
let hexSample = convert.textToHex(text)
//Result: 746573742074657874

//Convert hex to text
let textSample = convert.hexToUtf8(hex)
//Result: test text

note: Source from page


2
嗨,迪亚哥,欢迎来到 Stack Overflow。也许你可以添加一个指向该软件包的链接,甚至添加一个如何使用它的示例。 - dege

0
如果您想要一个带有0x前缀的漂亮十六进制数字字符串:
export function toHexString(value: Buffer | number[]): string {
  if(!value) return null;
  if(typeof value == "object") value = Buffer.from(value);
  return value.toString('hex').match(/.{1,2}/g).map(val => `0x${val}`).join(", ");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接