HEX to Base64 converter for JavaScript

后端 未结 5 1940
北海茫月
北海茫月 2020-12-01 09:25

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

5条回答
  •  自闭症患者
    2020-12-01 09:48

    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=="
    

提交回复
热议问题