Sfoglia il codice sorgente

a simple (and incomplete) base64 encoder

incomplete as in "does not base64 encode strings with a non-multiple of
3 length".

there must be a simpler way, though.
Lucas Stadler 11 anni fa
parent
commit
aa9220c149
1 ha cambiato i file con 46 aggiunte e 0 eliminazioni
  1. 46 0
      go/encode.go

+ 46 - 0
go/encode.go

@ -0,0 +1,46 @@
1
package main
2
3
import "fmt"
4
5
// encodes a six-bit integer (max = 2^6 - 1 = 63) as a character in A-Za-z0-9+/
6
func encode(b byte) byte {
7
	if b < 26 {
8
		return 'A' + b
9
	} else if b < 52 {
10
		return 'a' + (b - 26)
11
	} else if b < 62 {
12
		return '0' + (b - 52)
13
	} else if b == 62 {
14
		return '+'
15
	} else if b == 63 {
16
		return '/'
17
	} else {
18
		fmt.Println("oops")
19
		return ' '
20
	}
21
}
22
23
func base64encode(b []byte) []byte {
24
	res := make([]byte, len(b) / 3 * 4)
25
	//fmt.Println(len(b), "->", len(res))
26
	for i := 0; i < len(b); i += 3 {
27
		c1, c2, c3 := b[i], b[i+1], b[i+2]
28
		r1 := c1 >> 2
29
		r2 := ((c1 ^ (r1 << 2)) << 4) + (c2 >> 4)
30
		r3 := ((c2 ^ ((c2 >> 4) << 4)) << 2) + (c3 >> 6)
31
		r4 := c3 ^ ((c3 >> 6) << 6)
32
		//fmt.Println(i, c1, c2, c3)
33
		base := i + i / 3
34
		res[base + 0] = encode(r1)
35
		res[base + 1] = encode(r2)
36
		res[base + 2] = encode(r3)
37
		res[base + 3] = encode(r4)
38
	}
39
	return res
40
}
41
42
func main() {
43
	base64 := base64encode([]byte("Hello, World!  "))
44
	//                                          ^^     (padded to a multiple of three)
45
	fmt.Println(string(base64))
46
}