Blog · Encoding

Hex to Base64: How to Convert Between Formats

Convert hexadecimal strings to Base64 in JavaScript, Python, and the command line. Smaller output, URL-safe, and ready for APIs.

Hex is readable but wasteful. Every byte takes two hex characters, doubling the size. Base64 encodes the same data 33% more efficiently. When you are sending binary data over a network or storing it in JSON, converting hex to Base64 saves bandwidth and storage.

JavaScript

function hexToBase64(hex) {
  // Convert hex pairs to byte array
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
  }
  return btoa(String.fromCharCode(...bytes));
}

Python

import base64
raw_bytes = bytes.fromhex("48656c6c6f")
result = base64.b64encode(raw_bytes).decode()
# "SGVsbG8="

Command Line (Linux/Mac)

# Hex string to Base64
echo "48656c6c6f" | xxd -r -p | base64
# "SGVsbG8="

For quick conversions without writing code, use our free online Base64 tool. Paste hex, decode to raw bytes, then re-encode as Base64.

Convert hex to Base64 instantly

No code needed. Paste, convert, copy. All in your browser.

Open Base64 Tool