21

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

4 Answers 4

56

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')
Sign up to request clarification or add additional context in comments.

3 Comments

I have a base64 string that contains a colon and when I converted it to hex then back to base64 it would strip off the colon. This fixed it thanks!
This works in react-native just need to install yarn add buffer
To have an evenly spaced, 2-letter output, one can just do the following: Buffer.from('hello world', 'utf8').toString('hex').replace(/../g, '$& ')
8

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

Comments

2

NPM amrhextotext, simple converter text to hex and hex to text

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

1 Comment

Hi Diego welcome to SO, maybe you can add a link to the package or even adding an example how to use it
0

If you want a pretty hex string of numbers plotted with 0x prefix :

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(", ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.