简体   繁体   English

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

[英]How to convert String into Hex nodejs

I was looking for some standard function like hex to string but inverse, I want to convert String to Hex, but I only found this function ...我正在寻找一些标准函数,如十六进制到字符串,但相反,我想将字符串转换为十六进制,但我只找到了这个函数......

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

In NodeJS, use Buffer to convert string to hex.在 NodeJS 中,使用Buffer将字符串转换为十六进制。

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

Simple example about how it works:关于它如何工作的简单示例:

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

You can use function like the below:您可以使用如下函数:

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

NPM amrhextotext , simple converter text to hex and hex to text NPM amrhextotext ,简单的文本到十六进制和十六进制到文本的转换器

Install安装

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 : Source from page注意:来自页面的来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM