Base64Lib — BASE64 Encoding/Decoding

Encode and decode data using BASE64 encoding. Widely used for transmitting binary data in text-based formats such as JSON, XML, email attachments, and data URIs. Includes URL-safe variants and file operations.

CategoryCountDescription
Core2b64encode$, b64decode$
URL-Safe2b64urlencode$, b64urldecode$
Validation1b64valid
File Operations2b64encodefile$, b64decodefile
Error Handling1b64error
FeatureDescription
Standard BASE64Characters A–Z, a–z, 0–9, +, /, with = padding
URL-SafeReplaces + with -, / with _, removes = padding
File SupportEncode any binary file (images, PDFs, etc.) to/from BASE64
UTF-8All string operations use UTF-8 encoding
Size OverheadBASE64 increases data size by approximately 33%

Error Handling

All functions set an internal error code retrievable with b64error().

CodeConstantDescription
0ERR_NONENo error
1ERR_INVALID_BASE64Invalid BASE64 string (malformed or corrupt)
2ERR_INVALID_ARGUMENTInvalid argument (empty path, etc.)
3ERR_FILE_ERRORFile read/write error
FunctionSignatureDescription
b64error()b64error@Error code from last Base64Lib operation (0–3)
╯ plan9basic
encoded$ = b64decode$("invalid!!!")
if b64error() <> 0 then
    println "Decoding failed with error: "; b64error()
endif

Core Functions

FunctionSignatureDescription
b64encode$(input$)b64encode$@$Encode string to BASE64 (UTF-8 input)
b64decode$(base64$)b64decode$@$Decode BASE64 to string (returns UTF-8)
╯ plan9basic
' Encode a string
original$ = "Hello, World!"
encoded$ = b64encode$(original$)
println "Encoded: "; encoded$
' Output: SGVsbG8sIFdvcmxkIQ==

' Decode back
decoded$ = b64decode$(encoded$)
println "Decoded: "; decoded$
' Output: Hello, World!

' Round-trip test
original$ = "Plan9Basic is great!"
encoded$ = b64encode$(original$)
decoded$ = b64decode$(encoded$)
if decoded$ = original$ then
    println "Round-trip successful!"
endif
ⓘ Note: Empty string input returns empty string (valid case). b64decode$() returns empty string and sets error code on invalid input.

URL-Safe Functions

Standard BASE64 uses + and / which have special meaning in URLs. The URL-safe variant replaces these with - and _, and removes padding characters (=).

FunctionSignatureDescription
b64urlencode$(input$)b64urlencode$@$Encode to URL-safe BASE64 (- instead of +, _ instead of /, no padding)
b64urldecode$(base64$)b64urldecode$@$Decode URL-safe BASE64 (handles both standard and URL-safe input)
StandardURL-Safe
Character 62+-
Character 63/_
Padding= (present)Removed
╯ plan9basic
data$ = "user:password"

' Standard BASE64
standard$ = b64encode$(data$)
println "Standard: "; standard$

' URL-safe BASE64
safe$ = b64urlencode$(data$)
println "URL-safe: "; safe$

' Use in a URL
url$ = "https://api.example.com/auth?token=" + safe$
println url$

' Decode back (handles both formats)
decoded$ = b64urldecode$(safe$)
println "Decoded: "; decoded$  ' user:password

Validation

FunctionSignatureDescription
b64valid(input$)b64valid@$Check if string is valid BASE64 (1=valid, 0=invalid)

Validates: correct characters (A–Z, a–z, 0–9, +, /, =), length is multiple of 4, padding position and count are correct. Empty string is considered valid.

╯ plan9basic
' Validate before decoding
input$ = "SGVsbG8sIFdvcmxkIQ=="
if b64valid(input$) = 1 then
    println "Valid: "; b64decode$(input$)
else
    println "Invalid BASE64!"
endif

' Test various inputs
println "Empty:       "; b64valid("")       ' 1 (valid)
println "Valid:       "; b64valid("YWJj")   ' 1
println "Padded:      "; b64valid("YQ==")   ' 1
println "Invalid:     "; b64valid("!@#$")   ' 0
println "Bad length:  "; b64valid("abc")    ' 0
println "Bad padding: "; b64valid("a=bc")   ' 0

File Operations

FunctionSignatureDescription
b64encodefile$(filepath$)b64encodefile$@$Read binary file and encode to BASE64 (empty on error)
b64decodefile(base64$, filepath$)b64decodefile@$$Decode BASE64 and write to binary file (1=success, 0=failure)
╯ plan9basic
' Encode an image file to BASE64
imagePath$ = "photo.jpg"
encoded$ = b64encodefile$(imagePath$)

if b64error() = 0 then
    println "Encoded: "; len(encoded$); " characters"
    
    ' Create a data URI for HTML
    dataUri$ = "data:image/jpeg;base64," + encoded$
else
    println "Error: "; b64error()
endif

' Decode BASE64 data to a file
base64Data$ = "iVBORw0KGgoAAAANSUhEUg..."
result = b64decodefile(base64Data$, "output.png")

if result = 1 then
    println "File saved successfully!"
else
    println "Error saving: "; b64error()
endif
⚠ Warning: b64encodefile$() can encode any file type (images, PDFs, executables). Sets ERR_FILE_ERROR (3) if the file cannot be read, ERR_INVALID_ARGUMENT (2) if the path is empty.

Complete Examples

Simple Text Encoding/Decoding

╯ text_encode.bas
' Simple text encoding and decoding
println "=== BASE64 Text Example ==="

original$ = "Plan9Basic makes programming fun!"
println "Original: "; original$

encoded$ = b64encode$(original$)
println "Encoded:  "; encoded$

decoded$ = b64decode$(encoded$)
println "Decoded:  "; decoded$

if decoded$ = original$ then
    println ""
    println "Success! Round-trip completed."
endif

Configuration Data Storage

╯ config_storage.bas
' Store configuration as BASE64
println "=== Configuration Storage ==="

config$ = "server=192.168.1.100" + chr$(10)
config$ = config$ + "port=8080" + chr$(10)
config$ = config$ + "apikey=secret123"

println "Original config:"
println config$
println ""

encoded$ = b64encode$(config$)
println "Encoded (safe for storage):"
println encoded$
println ""

decoded$ = b64decode$(encoded$)
println "Decoded config:"
println decoded$

File Round-Trip

╯ file_roundtrip.bas
' Encode a file and decode it back
println "=== File Encoding ==="

sourceFile$ = "document.pdf"
destFile$ = "document_copy.pdf"

println "Encoding: "; sourceFile$
tempBase64$ = b64encodefile$(sourceFile$)

if b64error() <> 0 then
    println "Error reading file!"
    end
endif

println "Encoded size: "; len(tempBase64$); " characters"

println "Decoding to: "; destFile$
result = b64decodefile(tempBase64$, destFile$)

if result = 1 then
    println "File copied successfully via BASE64!"
else
    println "Error writing file!"
endif

URL-Safe Token Generation

╯ urlsafe_token.bas
' Generate URL-safe tokens for web applications
println "=== URL-Safe Token ==="

username$ = "john.doe@example.com"
timestamp$ = "2026-01-03T12:00:00"
data$ = username$ + ":" + timestamp$

standard$ = b64encode$(data$)
println "Standard:  "; standard$

urlsafe$ = b64urlencode$(data$)
println "URL-safe:  "; urlsafe$

url$ = "https://api.example.com/verify?token=" + urlsafe$
println ""
println "URL: "; url$

decoded$ = b64urldecode$(urlsafe$)
println "Decoded: "; decoded$

Input Validation

╯ validation.bas
' Validate BASE64 before processing
println "=== Validation ==="

function testResult$(value) local r$
    if value = 1 then
        r$ = "VALID"
    else
        r$ = "INVALID"
    endif
    return r$
endfunction

println "Empty string:   "; testResult$(b64valid(""))
println "Valid (YWJj):   "; testResult$(b64valid("YWJj"))
println "Valid (padded): "; testResult$(b64valid("YQ=="))
println "Invalid (!@#):  "; testResult$(b64valid("!@#$"))
println "Bad length:     "; testResult$(b64valid("abc"))
println "Bad padding:    "; testResult$(b64valid("a=bc"))

println ""
userInput$ = "SGVsbG8sIFdvcmxkIQ=="
if b64valid(userInput$) = 1 then
    println "Decoded: "; b64decode$(userInput$)
else
    println "Cannot decode - invalid BASE64!"
endif

What is BASE64?

BASE64 is an encoding scheme that converts binary data into text using 64 printable ASCII characters. It’s used when binary data needs to be transmitted over text-only systems.

Character SetCharacters
UppercaseA–Z (26)
Lowercasea–z (26)
Digits0–9 (10)
Symbols+ and / (2)
Padding=

How it works: Take 3 bytes (24 bits) of input, split into 4 groups of 6 bits, convert each to one BASE64 character. If input isn’t divisible by 3, add = padding. This results in approximately 33% size increase (4 output characters per 3 input bytes).

Quick Reference

FunctionSignatureDescription
b64error()b64error@Last error code (0=none, 1=invalid base64, 2=bad arg, 3=file error)
b64encode$(input$)b64encode$@$Encode string to BASE64
b64decode$(base64$)b64decode$@$Decode BASE64 to string
b64urlencode$(input$)b64urlencode$@$Encode to URL-safe BASE64
b64urldecode$(base64$)b64urldecode$@$Decode URL-safe BASE64
b64valid(input$)b64valid@$Validate BASE64 string (1/0)
b64encodefile$(filepath$)b64encodefile$@$Encode file to BASE64
b64decodefile(base64$, path$)b64decodefile@$$Decode BASE64 to file (1/0)

8 functions across 5 categories.