Base64 in Programming Languages

Every major programming language has built-in support for Base64 encoding and decoding. Here are practical examples you can copy and use right away.

JavaScript / Node.js

JavaScript provides btoa() and atob() functions in the browser. For Node.js, use the Buffer class. See the MDN documentation for btoa().

Browser (btoa/atob)

browser.js
// Encode to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode from Base64
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"

// Handle Unicode (UTF-8) - btoa only works with ASCII
function encodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    (match, p1) => String.fromCharCode('0x' + p1)
  ));
}

function decodeUnicode(str) {
  return decodeURIComponent(atob(str).split('').map(
    c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
  ).join(''));
}

Node.js (Buffer)

node.js
// Encode to Base64
const encoded = Buffer.from('Hello, World!').toString('base64');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode from Base64
const decoded = Buffer.from('SGVsbG8sIFdvcmxkIQ==', 'base64').toString('utf-8');
console.log(decoded); // "Hello, World!"

// Base64URL encoding (URL-safe)
const base64url = Buffer.from('Hello').toString('base64url');

// Encode a file
const fs = require('fs');
const fileBase64 = fs.readFileSync('image.png').toString('base64');

Python

Python's base64 module provides all the encoding variants. See the official Python documentation.

base64_example.py
import base64

# Encode to Base64
text = "Hello, World!"
encoded = base64.b64encode(text.encode('utf-8')).decode('utf-8')
print(encoded)  # "SGVsbG8sIFdvcmxkIQ=="

# Decode from Base64
decoded = base64.b64decode('SGVsbG8sIFdvcmxkIQ==').decode('utf-8')
print(decoded)  # "Hello, World!"

# Base64URL encoding (for URLs and filenames)
encoded_url = base64.urlsafe_b64encode(text.encode()).decode()
decoded_url = base64.urlsafe_b64decode(encoded_url).decode()

# Encode a file
with open('image.png', 'rb') as f:
    encoded_file = base64.b64encode(f.read()).decode()

# Decode to a file
with open('output.png', 'wb') as f:
    f.write(base64.b64decode(encoded_file))

Java

Java 8+ includes java.util.Base64. For older versions, use Apache Commons Codec. See the Java 8 Base64 documentation.

Base64Example.java
import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class Base64Example {
    public static void main(String[] args) {
        String text = "Hello, World!";
        
        // Encode to Base64
        String encoded = Base64.getEncoder()
            .encodeToString(text.getBytes(StandardCharsets.UTF_8));
        System.out.println(encoded); // "SGVsbG8sIFdvcmxkIQ=="
        
        // Decode from Base64
        byte[] decodedBytes = Base64.getDecoder()
            .decode("SGVsbG8sIFdvcmxkIQ==");
        String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
        System.out.println(decoded); // "Hello, World!"
        
        // Base64URL encoding (URL-safe, no padding)
        String encodedUrl = Base64.getUrlEncoder()
            .withoutPadding()
            .encodeToString(text.getBytes());
        
        // MIME encoding (with line breaks every 76 chars)
        String encodedMime = Base64.getMimeEncoder()
            .encodeToString(text.getBytes());
    }
}

PHP

PHP has simple base64_encode() and base64_decode() functions. See the PHP documentation.

base64_example.php
<?php
// Encode to Base64
$text = "Hello, World!";
$encoded = base64_encode($text);
echo $encoded; // "SGVsbG8sIFdvcmxkIQ=="

// Decode from Base64
$decoded = base64_decode('SGVsbG8sIFdvcmxkIQ==');
echo $decoded; // "Hello, World!"

// Encode a file to Data URI
$imageData = base64_encode(file_get_contents('image.png'));
$dataUri = 'data:image/png;base64,' . $imageData;

// Validate Base64 string
function isValidBase64($string) {
    return base64_encode(base64_decode($string, true)) === $string;
}

// URL-safe Base64 (manual conversion)
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
    return base64_decode(strtr($data, '-_', '+/'));
}
?>

C# / .NET

.NET uses Convert.ToBase64String() and Convert.FromBase64String(). See the Microsoft documentation.

Base64Example.cs
using System;
using System.Text;

class Base64Example
{
    static void Main()
    {
        string text = "Hello, World!";
        
        // Encode to Base64
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        string encoded = Convert.ToBase64String(bytes);
        Console.WriteLine(encoded); // "SGVsbG8sIFdvcmxkIQ=="
        
        // Decode from Base64
        byte[] decodedBytes = Convert.FromBase64String("SGVsbG8sIFdvcmxkIQ==");
        string decoded = Encoding.UTF8.GetString(decodedBytes);
        Console.WriteLine(decoded); // "Hello, World!"
        
        // Encode a file
        byte[] fileBytes = File.ReadAllBytes("image.png");
        string encodedFile = Convert.ToBase64String(fileBytes);
        
        // Decode to a file
        File.WriteAllBytes("output.png", Convert.FromBase64String(encodedFile));
    }
}

Go

Go's encoding/base64 package supports all variants. See the Go package documentation.

main.go
package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    text := "Hello, World!"
    
    // Encode to Base64
    encoded := base64.StdEncoding.EncodeToString([]byte(text))
    fmt.Println(encoded) // "SGVsbG8sIFdvcmxkIQ=="
    
    // Decode from Base64
    decoded, err := base64.StdEncoding.DecodeString("SGVsbG8sIFdvcmxkIQ==")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(decoded)) // "Hello, World!"
    
    // Base64URL encoding (URL-safe)
    encodedUrl := base64.URLEncoding.EncodeToString([]byte(text))
    
    // Raw encoding (no padding)
    encodedRaw := base64.RawStdEncoding.EncodeToString([]byte(text))
    encodedRawUrl := base64.RawURLEncoding.EncodeToString([]byte(text))
}

Ruby

Ruby's Base64 module is part of the standard library. See the Ruby documentation.

base64_example.rb
require 'base64'

# Encode to Base64 (with line breaks)
text = "Hello, World!"
encoded = Base64.encode64(text)
puts encoded.chomp  # "SGVsbG8sIFdvcmxkIQ=="

# Strict encoding (no line breaks)
encoded_strict = Base64.strict_encode64(text)

# Decode from Base64
decoded = Base64.decode64('SGVsbG8sIFdvcmxkIQ==')
puts decoded  # "Hello, World!"

# Base64URL encoding (URL-safe)
encoded_url = Base64.urlsafe_encode64(text)
decoded_url = Base64.urlsafe_decode64(encoded_url)

# Encode a file
file_data = Base64.strict_encode64(File.read('image.png', mode: 'rb'))

Command Line

Linux / macOS

Terminal
# Encode a string
echo -n "Hello, World!" | base64
# Output: SGVsbG8sIFdvcmxkIQ==

# Decode a string
echo "SGVsbG8sIFdvcmxkIQ==" | base64 -d
# Output: Hello, World!

# Encode a file
base64 image.png > image.b64

# Decode a file
base64 -d image.b64 > image_decoded.png

# macOS uses -D instead of -d
echo "SGVsbG8=" | base64 -D

# Pipe to clipboard (macOS)
echo -n "Hello" | base64 | pbcopy

Windows PowerShell

PowerShell
# Encode a string
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Hello, World!"))
# Output: SGVsbG8sIFdvcmxkIQ==

# Decode a string
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("SGVsbG8sIFdvcmxkIQ=="))
# Output: Hello, World!

# Encode a file
[Convert]::ToBase64String([IO.File]::ReadAllBytes("image.png"))

# Decode to a file
[IO.File]::WriteAllBytes("output.png", [Convert]::FromBase64String($base64String))

Quick Reference Table

LanguageEncodeDecode
JavaScriptbtoa(str)atob(str)
Node.jsBuffer.from(str).toString('base64')Buffer.from(str, 'base64').toString()
Pythonbase64.b64encode()base64.b64decode()
JavaBase64.getEncoder().encodeToString()Base64.getDecoder().decode()
PHPbase64_encode()base64_decode()
C#Convert.ToBase64String()Convert.FromBase64String()
Gobase64.StdEncoding.EncodeToString()base64.StdEncoding.DecodeString()
RubyBase64.strict_encode64()Base64.decode64()
Bashecho -n "str" | base64echo "str" | base64 -d

No Code Needed?

For quick encoding/decoding without writing code, use our free online tool. It works entirely in your browser—your data never leaves your computer.

Open Encoder/Decoder →