base64

This module implements a base64 encoder and decoder.

Unstable API.

Base64 is an encoding and decoding technique used to convert binary data to an ASCII string format. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits.

Basic usage

Encoding data

import base64
let encoded = encode("Hello World")
assert encoded == "SGVsbG8gV29ybGQ="

Apart from strings you can also encode lists of integers or characters:

import base64
let encodedInts = encode([1,2,3])
assert encodedInts == "AQID"
let encodedChars = encode(['h','e','y'])
assert encodedChars == "aGV5"

Decoding data

import base64
let decoded = decode("SGVsbG8gV29ybGQ=")
assert decoded == "Hello World"

See also

  • hashes module for efficient computations of hash values for diverse Nim types
  • md5 module implements the MD5 checksum algorithm
  • sha1 module implements a sha1 encoder and decoder

Procs

proc encode[T: SomeInteger | char](s: openArray[T]; lineLen = 75; newLine = ""): string

Encodes s into base64 representation. After lineLen characters, a newline is added.

This procedure encodes an openarray (array or sequence) of either integers or characters.

See also:

Examples:

assert encode(['n', 'i', 'm']) == "bmlt"
assert encode(@['n', 'i', 'm']) == "bmlt"
assert encode([1, 2, 3, 4, 5]) == "AQIDBAU="
  Source Edit
proc encode(s: string; lineLen = 75; newLine = ""): string {...}{.raises: [], tags: [].}

Encodes s into base64 representation. After lineLen characters, a newline is added.

This procedure encodes a string.

See also:

Examples:

assert encode("Hello World") == "SGVsbG8gV29ybGQ="
assert encode("Hello World", 3, "\n") == "SGVs\nbG8g\nV29ybGQ="
  Source Edit
proc decode(s: string): string {...}{.raises: [], tags: [].}

Decodes string s in base64 representation back into its original form. The initial whitespace is skipped.

See also:

Examples:

assert decode("SGVsbG8gV29ybGQ=") == "Hello World"
assert decode("  SGVsbG8gV29ybGQ=") == "Hello World"
  Source Edit