Base64 Encode Decode in Tcl

Published on 08 October 2025 (Updated: 08 October 2025)

Welcome to the Base64 Encode Decode in Tcl page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

#!/usr/bin/env tclsh

proc usage {} {
    puts stderr "Usage: please provide a mode and a string to encode/decode"
    exit 1
}

if {$argc != 2} {
    usage
}

set mode [lindex $argv 0]
set text [lindex $argv 1]

if {$text eq ""} {
    usage
}


switch -- $mode {
    encode {
        set result [binary encode base64 $text]
    }
    decode {
        if {[catch {binary decode base64 $text} result]} {
            usage
        }
	# Tcl’s decoder sometimes tolerates invalid padding, so validate manually
        # Check that input length is a multiple of 4 and only contains valid chars
        if {![regexp {^[A-Za-z0-9+/]*={0,2}$} $text]} {
            usage
        }
        if {[expr {[string length $text] % 4 != 0}]} {
            usage
        }
    }
    default {
        usage
    }
}

puts $result


Base64 Encode Decode in Tcl was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.