14

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

2 Answers2

33

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

https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

To get the byte (0-255) value:

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

And to convert back:

Buffer.from([128]).toString('hex');
// outputs '80'

To convert to utf8:

Buffer.from('80', 'hex').toString('utf8');
Ben Taber
  • 6,426
  • 1
  • 22
  • 17
  • Would this work for multiple hex values? (I actually have several hex values that make up the string) –  Apr 07 '14 at 12:17
  • Yes, definitely. It will work with a hex encoded string of any length. You can get the bytes at each position using the `[n]` notation, and can convert the entire string to a utf8 representation via `.toString('utf8')`. – Ben Taber Apr 07 '14 at 23:43
  • 2
    Since Node.js 6.0.0, the `new Buffer(size)` was deprecated. Please use `Buffer.alloc(16, 'hex').toString('utf8')` instead – Ryan Wu Aug 23 '17 at 18:06
  • is utf8 safe to use? Ideally we want the equivalent of MySQL's unhex() function. So "F1F2F3F4" becomes 0xF1F2F3F4. 00-FF only as per Latin1 or Binary. Anything above 8 bit is next layer. – mckenzm Nov 04 '21 at 23:51
6

You can make use of Number.prototype.toString and parseInt.

The key is to make use of the radix parameters to do the conversions for you.

var bytestring = Number('0x' + hexstring).toString(10);    // '128'
parseInt(bytestring, 2).toString(16);  // '80'

thgaskell
  • 12,772
  • 5
  • 32
  • 38
  • 1
    byte != binary, so not what I am needing. –  Apr 07 '14 at 02:08
  • 2
    huh, i know it's super late, but i fixed the `parseInt` to convert to decimal instead of binary. thanks kind stranger for the down vote to bring my attention to this! – thgaskell Jul 30 '16 at 08:11
  • This is still incorrect. Hexidecimal 'hex string' is 16 radix. Additionally, it's not possible to get a true byte from these methods. This returns a string in browser and node. and operates on an integer. Maybe, with the new `Int8Array` typed Arrays this could be possible. Untested. `parseInt('0x80', 16); // 128` and `(128).toString(16); // '80'` – gtzilla Sep 26 '18 at 06:37