Hex to String & String to Hex conversion in nodejs

21,163

You need to use Buffer.from() for decoding as well. Consider writing a higher-order function to reduce the amount of repeated code:

const convert = (from, to) => str => Buffer.from(str, from).toString(to)
const utf8ToHex = convert('utf8', 'hex')
const hexToUtf8 = convert('hex', 'utf8')

hexToUtf8(utf8ToHex('dailyfile.host')) === 'dailyfile.host'
Share:
21,163
Hassaan
Author by

Hassaan

I am available for Freelance hire. "[email protected]"

Updated on July 18, 2022

Comments

  • Hassaan
    Hassaan almost 2 years

    I need to convert data into String to Hex and then again from Hex to String using nodejs 8

    I have issue while decoding from Hex to String

    Code to convert string into hex

    function stringToHex(str)
    {
        const buf = Buffer.from(str, 'utf8');
        return buf.toString('hex');
    }
    

    Code to convert hex into string

    function hexToString(str)
    {
        const buf = new Buffer(str, 'hex');
        return buf.toString('utf8');
    }
    

    I have string dailyfile.host

    output of encoding: 3162316637526b62784a5a37697a45796c656d465643747a4a505a6f59774641534c75714733544b4446553d

    output of decoding: 1b1f7RkbxJZ7izEylemFVCtzJPZoYwFASLuqG3TKDFU=

    Required output of decoding: dailyfile.host

  • Hassaan
    Hassaan over 5 years
    This still does not work for me, I am using nodejs v8.11.
  • Patrick Roberts
    Patrick Roberts over 5 years
    @Hassaan "This does not work" is not a problem statement. Be more specific about the issue you're having.
  • Hassaan
    Hassaan over 5 years
    Issue is still the same while decoding. Encoded string 4d6a772b646e316c4e314867684c435431724a53674e5934303063336752‌​74474753506742672f62‌​2b4f6b3d but decoded string is Mjw+dn1lN1HghLCT1rJSgNY400c3gRtGGSPgBg/b+Ok=
  • Patrick Roberts
    Patrick Roberts over 5 years
    That's because your hexadecimal string is the hex encoding of that output string. What's the output of utf8ToHex('dailyfile.host')? It should be 6461696c7966696c652e686f7374.
  • Hassaan
    Hassaan over 5 years
    I see, how to resolve it? Can you please update answer for this?
  • Patrick Roberts
    Patrick Roberts over 5 years
    Where is that "encoded string" coming from? Can you update your question to clarify?
  • Hassaan
    Hassaan over 5 years
    I am giving string to as parameter of GET request to URL. I am updating my question
  • Hassaan
    Hassaan over 5 years
    I have tested your provided answer as sandbox. Its working fine but there was issue with my code as you mentioned in above comment. I was using @skavinvarnan/cryptlib module for encryption and while while decoding I was not using that module. Thanks man for pointing me in right way :)
  • krupesh Anadkat
    krupesh Anadkat over 3 years
    Just check that hex string doesnot start with '0x', and above code should work while converting from hex to utf8