shaun5 shaun5 - 1 year ago 118
Javascript Question

How to convert a hex string to a byte and a byte to a hex string in Javascript?

How do you convert a hex code represented in a string to a byte and the reverse in Javascript?

var conv = require('binstring');
var hexstring ='80';
var bytestring = conv(hexstring, {in:'hex', out:'utf8'});
var backtohexstring = conv(bytestring, {in:'utf8', out:'hex'}); // != '80'???

backtohexstring decodes an incoming data string to the correct hex (I also used utf8 vs. byte, because it 'looked' like the incoming string when printed to the console), so I'm confused...

I also found these two native javascript functions, the decoder works on my incoming stream, but I still can't get the hex to encode...

function encode_utf8( s ) {
return unescape( encodeURIComponent( s ) );
function decode_utf8( s ) {
return decodeURIComponent( escape( s ) );

Answer Source

Here's a node.js specific approach, taking advantage of the the Buffer class provided by the node standard lib.

To get the byte (0-255) value:

new Buffer('80', 'hex')[0];
// outputs 128

And to convert back:

var b = new Buffer(1);
b[0] = 128;
// outputs '80'

To convert to utf8:

new Buffer('80', 'hex').toString('utf8');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download