forked from ruudk/golang-pdf417
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_encoder.go
87 lines (62 loc) · 1.41 KB
/
number_encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package pdf417
import (
"regexp"
"math"
"math/big"
)
const NUMBER_SWITCH_CODE_WORD int = 902
type NumberEncoder struct {
}
func CreateNumberEncoder() *NumberEncoder {
return new(NumberEncoder)
}
func (encoder NumberEncoder) GetName() string {
return "number"
}
func (encoder NumberEncoder) CanEncode(char string) bool {
match, err := regexp.MatchString("^[0-9]{1}$", char)
if err != nil {
return false
}
return match
}
func (encoder NumberEncoder) GetSwitchCode(data string) int {
return NUMBER_SWITCH_CODE_WORD
}
func (encoder NumberEncoder) Encode(digits string, addSwitchCode bool) []int {
digitCount := len(digits)
chunkCount := int(math.Ceil(float64(digitCount) / float64(44)))
codeWords := []int{}
if (addSwitchCode) {
codeWords = append(codeWords, NUMBER_SWITCH_CODE_WORD)
}
for i := 0; i < chunkCount; i++ {
start := i * 44
end := start + 44
if end > digitCount {
end = digitCount
}
chunk := digits[start:end]
cws := encodeChunk(chunk)
codeWords = append(codeWords, cws...)
}
return codeWords
}
func encodeChunk(chunkInput string) []int {
chunk := big.NewInt(0)
_, ok := chunk.SetString("1" + chunkInput, 10)
if ! ok {
panic("Failed converting")
}
cws := []int{}
for chunk.Cmp(big.NewInt(0)) > 0 {
newChunk, cw := chunk.DivMod(
chunk,
big.NewInt(900),
big.NewInt(0),
)
chunk = newChunk
cws = append([]int{int(cw.Int64())}, cws...)
}
return cws
}