-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
63 lines (51 loc) · 995 Bytes
/
encode.go
File metadata and controls
63 lines (51 loc) · 995 Bytes
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
package packeddecimal
import (
"errors"
"fmt"
"strconv"
)
// Encode func(n int, size int) ([]byte, error).
func Encode(n int, size int) ([]byte, error) {
res := make([]byte, size)
s := fmt.Sprint(n)
length := len(s)
isNegative := n < 0
if isNegative {
s = s[1:]
length--
}
if length > 2*size-1 {
return res, errors.New("index out of range")
}
if length%2 == 0 {
s = "0" + s
length++
}
neededBytes := ((length + 1) / 2) + (1 / 2)
extraBytes := neededBytes - size
if extraBytes < 0 {
for i := 0; i < -extraBytes; i++ {
res[i] = 0x00
}
} else if extraBytes > 0 {
s = s[extraBytes:]
length -= extraBytes
extraBytes = 0
}
var pos int
for i := 0; i < length; i++ {
digit, _ := strconv.Atoi(s[i : i+1])
pos = (i / 2) - extraBytes
if i%2 == 0 {
res[pos] = byte(digit << 4)
} else {
res[pos] = res[pos] | (byte(digit) & 0x0f)
}
}
if isNegative {
res[size-1] |= minusSign
} else {
res[size-1] |= plusSign
}
return res, nil
}