Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 943
DarckBlezzer Avatar asked Nov 27 '17 23:11

DarckBlezzer


2 Answers

In NodeJS, use Buffer to convert string to hex.

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')
like image 117
Luis Estevez Avatar answered Oct 02 '22 04:10

Luis Estevez


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'); 
like image 34
nirazlatu Avatar answered Oct 02 '22 04:10

nirazlatu