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'
Comments
-
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 over 5 yearsThis still does not work for me, I am using
nodejs v8.11
. -
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 over 5 yearsIssue is still the same while decoding. Encoded string
4d6a772b646e316c4e314867684c435431724a53674e593430306333675274474753506742672f622b4f6b3d
but decoded string isMjw+dn1lN1HghLCT1rJSgNY400c3gRtGGSPgBg/b+Ok=
-
Patrick Roberts over 5 yearsThat's because your hexadecimal string is the hex encoding of that output string. What's the output of
utf8ToHex('dailyfile.host')
? It should be6461696c7966696c652e686f7374
. -
Hassaan over 5 yearsI see, how to resolve it? Can you please update answer for this?
-
Patrick Roberts over 5 yearsWhere is that "encoded string" coming from? Can you update your question to clarify?
-
Hassaan over 5 yearsI am giving string to as parameter of GET request to URL. I am updating my question
-
Hassaan over 5 yearsI 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 over 3 yearsJust check that hex string doesnot start with '0x', and above code should work while converting from hex to utf8