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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47521730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:35:57  来源:igfitidea点击:

How to convert String into Hex nodejs

node.jsstringhex

提问by DarckBlezzer

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

回答by Luis Estevez

In NodeJS, use Bufferto 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')

回答by Niraj Paudel

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

回答by Diego

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

注意:来自页面的来源