1# -*- tcl -*-
2# This code is hereby put into the public domain.
3# ### ### ### ######### ######### #########
4## Overview
5# Base32 encoding and decoding of small strings.
6
7# ### ### ### ######### ######### #########
8## Notes
9
10# A binary string is split into groups of 5 bits (2^5 == 32), and each
11# group is converted into a printable character as is specified in RFC
12# 3548 for the extended hex encoding.
13
14# ### ### ### ######### ######### #########
15## Requisites
16
17package require  base32::core
18namespace eval ::base32::hex {}
19
20# ### ### ### ######### ######### #########
21## API & Implementation
22
23proc ::base32::hex::tcl_encode {bitstring} {
24    variable forward
25
26    binary scan $bitstring B* bits
27    set len [string length $bits]
28    set rem [expr {$len % 5}]
29    if {$rem} {append bits =/$rem}
30    #puts "($bitstring) => <$bits>"
31
32    return [string map $forward $bits]
33}
34
35proc ::base32::hex::tcl_decode {estring} {
36    variable backward
37    variable invalid
38
39    if {![core::valid $estring $invalid msg]} {
40	return -code error $msg
41    }
42    #puts "I<$estring>"
43    #puts "M<[string map $backward $estring]>"
44
45    return [binary format B* [string map $backward [string toupper $estring]]]
46}
47
48# ### ### ### ######### ######### #########
49## Data structures
50
51namespace eval ::base32::hex {
52    namespace eval core {
53	namespace import ::base32::core::define
54	namespace import ::base32::core::valid
55    }
56
57    namespace export encode decode
58    # Initialize the maps
59    variable forward
60    variable backward
61    variable invalid
62
63    core::define {
64	0 0    9 9        18 I   27 R
65	1 1   10 A        19 J   28 S
66	2 2   11 B        20 K   29 T
67	3 3   12 C        21 L   30 U
68	4 4   13 D        22 M   31 V
69	5 5   14 E        23 N
70	6 6   15 F        24 O
71	7 7        16 G   25 P
72	8 8        17 H   26 Q
73    } forward backward invalid ; # {}
74    # puts ///$forward///
75    # puts ///$backward///
76}
77
78# ### ### ### ######### ######### #########
79## Ok
80