美文网首页web前端
js实现16进制转换为Base64

js实现16进制转换为Base64

作者: 侬姝沁儿 | 来源:发表于2019-11-10 16:01 被阅读0次

新建文件HexToBase64.js,内容如下:

const HexToBase64 = (sha1) => {
  var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  var base64_rep = ""
  var ascv
  var bit_arr = 0
  var bit_num = 0

  for (var n = 0; n < sha1.length; ++n) {
    if (sha1[n] >= 'A' && sha1[n] <= 'Z') {
      ascv = sha1.charCodeAt(n) - 55
    } else if (sha1[n] >= 'a' && sha1[n] <= 'z') {
      ascv = sha1.charCodeAt(n) - 87
    } else {
      ascv = sha1.charCodeAt(n) - 48
    }

    bit_arr = (bit_arr << 4) | ascv
    bit_num += 4
    if (bit_num >= 6) {
      bit_num -= 6

      base64_rep += digits[bit_arr >>> bit_num]
      bit_arr &= ~ (-1 << bit_num)
    }
  }

  if (bit_num > 0) {
    bit_arr <<= 6 - bit_num
    base64_rep += digits[bit_arr]
  }
  var padding = base64_rep.length % 4

  if (padding > 0) {
    for (var n = 0; n < 4 - padding; ++n) {
      base64_rep += "="
    }
  }
  return base64_rep
}

export default HexToBase64

使用 import ... form ...

相关文章

网友评论

    本文标题:js实现16进制转换为Base64

    本文链接:https://www.haomeiwen.com/subject/ytmgbctx.html