JavaScript で hex string と Base64 の相互変換
hex string から base64
code:hexToBase64.js
const hex = "442032b9858d7509f18ee9fc39fca3153cd733476ab348767aa5e57dcb9d7a08"
// いったん Uint8Array に変換
const a = new Uint8Array(hex.match(/.{1,2}/g).map(v => parseInt(v, 16)))
// Base64 に変換
const base64 = btoa(String.fromCharCode.apply(null, a))
console.log(base64)
// => RCAyuYWNdQnxjun8OfyjFTzXM0dqs0h2eqXlfcudegg=
alert(base64)
base64 から hex string
code:base64ToHex.js
const base64 = "RCAyuYWNdQnxjun8OfyjFTzXM0dqs0h2eqXlfcudegg="
// いったん Uint8Array に変換
const a = new Uint8Array(atob(base64).split("").map(function(c){return c.charCodeAt(0);}));
// hex に変換
const hex = Array.from(a).map(v => v.toString(16).padStart(2, "0")).join('')
console.log(hex)
// => 442032b9858d7509f18ee9fc39fca3153cd733476ab348767aa5e57dcb9d7a08
alert(hex)
node.js
code:js
const hex = "442032b9858d7509f18ee9fc39fca3153cd733476ab348767aa5e57dcb9d7a08"
const buf = Buffer.from(hex, 'hex')
const base64 = buf.toString('base64')
console.log(base64)
//=> RCAyuYWNdQnxjun8OfyjFTzXM0dqs0h2eqXlfcudegg=