如何将String转换为Hex nodejs

问题描述 投票:9回答:3

我正在寻找一些标准函数,例如将十六进制字符串化,但是取反,我想将String转换为Hex,但我只找到了此function ...

// example of convert hex to String
hex.toString('utf-8')
node.js string hex
3个回答
20
投票

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

3
投票

您可以使用如下功能:

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

0
投票

NPM amrhextotext,简单的转换文本为十六进制和十六进制为文本

安装

npm i amrhextotext

Usange:

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:页面来源

© www.soinside.com 2019 - 2024. All rights reserved.