Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex to String & String to Hex conversion in nodejs

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

like image 968
Hassaan Avatar asked Sep 10 '18 15:09

Hassaan


People also ask

How do you convert hexadecimal to string?

In order to convert a hex string into a normal string, the hex string has to be converted into a byte array, which is indexed and converted into smaller hex strings of two digits. The smaller hex strings are then concatenated into a normal string. For some values, a two digit hex string will start with a zero.

How long is a hex string?

The maximum 4-digit hexadecimal number is FFFF16 which is equal to 65,535 in decimal and so on as the number of digits increase.

Why is hex a string python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.

How do you read hex characters?

The first nine numbers (0 to 9) are the same ones commonly used in the decimal system. The next six two-digit numbers (10 to 15) are represented by the letters A through F. This is how the hex system uses the numbers from 0 to 9 and the capital letters A to F to represent the equivalent decimal number.


1 Answers

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'
like image 97
Patrick Roberts Avatar answered Sep 17 '22 13:09

Patrick Roberts