Decode Base64 to Hexadecimal string with javascript

前端 未结 5 1168
有刺的猬
有刺的猬 2020-12-06 09:52

Needing to convert a Base64 string to Hexadecimal with javascript.

Example:

var base64Value = \"oAAABTUAAg==\"

Need conversion m

5条回答
  •  攒了一身酷
    2020-12-06 10:36

    Assuming you want the hexadecimal representation as a string, the window.atob function (available in most modern browsers) is your first step - it will convert your base64 string to an ASCII string, where each character represents one byte.

    At this point you split the string, grab the character code of each character, then convert that to a left-padded base-16 string.

    function base64ToBase16(base64) {
      return window.atob(base64)
          .split('')
          .map(function (aChar) {
            return ('0' + aChar.charCodeAt(0).toString(16)).slice(-2);
          })
         .join('')
         .toUpperCase(); // Per your example output
    }
    
    console.log(base64ToBase16("oAAABTUAAg==")); // "A0000005350002"

    (Or try it on JSBin)

提交回复
热议问题