使用 javascript 将 Base64 解码为十六进制字符串

2022-01-21 00:00:00 hex base64 javascript

需要使用 javascript 将 Base64 字符串转换为十六进制.

Needing to convert a Base64 string to Hexadecimal with javascript.

例子:

var base64Value = "oAAABTUAAg=="

需要转换方法

输出(解码数据(十六进制))A0000005350002

Output (Decoded data (hexadecimal)) A0000005350002

我知道这是正确的,因为我可以使用这个网站 http://tomeko.net/online_tools/base64.php?lang=en

I know this is correct because I can use this website http://tomeko.net/online_tools/base64.php?lang=en

输入oAAABTUAAg==的Base64字符串,得到A0000005350002

and punch in Base64 string of oAAABTUAAg== and get A0000005350002

我尝试了什么?

https://github.com/carlo/jquery-base64
https://jsfiddle.net/gabrieleromanato/qaght/

我发现了很多问题

推荐答案

atob() 然后 charCodeAt() 会给你二进制 &toString(16) 会给你十六进制.

atob() then charCodeAt() will give you binary & toString(16) will give you hex.

function base64ToHex(str) {
  const raw = atob(str);
  let result = '';
  for (let i = 0; i < raw.length; i++) {
    const hex = raw.charCodeAt(i).toString(16);
    result += (hex.length === 2 ? hex : '0' + hex);
  }
  return result.toUpperCase();
}

console.log(base64ToHex("oAAABTUAAg=="));

相关文章