Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HEX to Base64 converter for JavaScript

Anyone know of a good snippet of JavaScript code to convert HEX encoded strings to base64 encoded strings?

like image 372
Chris Dutrow Avatar asked Apr 21 '14 02:04

Chris Dutrow


People also ask

What is Base64 in Javascript?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Why is BTOA deprecated?

btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.


2 Answers

If you're working in Node or using Browserify, you can use

var base64String = Buffer.from(hexString, 'hex').toString('base64') 

or

var hexString = Buffer.from(base64String, 'base64').toString('hex') 
like image 120
Tim Avatar answered Sep 22 '22 04:09

Tim


The excellent comment by @dandavis is modified by StackOverflow, and has some weird hidden characters.

Here it is as one liner :

btoa("a6b580481008e60df9350de170b7e728".match(/\w{2}/g).map(function(a){return String.fromCharCode(parseInt(a, 16));} ).join("")) 

or :

function hexToBase64(hexstring) {     return btoa(hexstring.match(/\w{2}/g).map(function(a) {         return String.fromCharCode(parseInt(a, 16));     }).join("")); }  hexToBase64("a6b580481008e60df9350de170b7e728"); 

Both return :

"prWASBAI5g35NQ3hcLfnKA==" 

Note that the hex string should have an even length :

hexToBase64("00"); // => "AA==" hexToBase64("000"); // => "AA==" 
like image 36
Eric Duminil Avatar answered Sep 23 '22 04:09

Eric Duminil