-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
95 lines (82 loc) · 1.54 KB
/
utils.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
88
89
90
91
92
93
94
95
package fpc
import (
"bytes"
"encoding/binary"
"strconv"
"strings"
)
// Utilities for using binary string representations of values
func bytes2binstr(bs []byte) string {
var ss []string
for _, b := range bs {
s := strconv.FormatUint(uint64(b), 2)
for len(s) < 8 {
s = "0" + s
}
ss = append(ss, s)
}
return strings.Join(ss, " ")
}
func binstr2bytes(s string) []byte {
s = strings.Replace(s, " ", "", -1)
var bs []byte
for len(s) > 0 {
end := 8
if 8 > len(s) {
end = len(s)
}
val, err := strconv.ParseUint(s[:end], 2, 8)
if err != nil {
panic(err)
}
bs = append(bs, byte(val))
s = s[end:]
}
return bs
}
func bytes2u64(b []byte) uint64 {
return binary.LittleEndian.Uint64(b)
}
func u642binstr(x uint64) string {
s := strconv.FormatUint(x, 2)
for len(s) < 64 {
s = "0" + s
}
return insertNth(s, 8)
}
func u82binstr(x uint8) string {
s := strconv.FormatUint(uint64(x), 2)
for len(s) < 8 {
s = "0" + s
}
return s
}
func insertNth(s string, n int) string {
var buffer bytes.Buffer
for i, rune := range s {
buffer.WriteRune(rune)
if i%n == n-1 && i != len(s)-1 {
buffer.WriteRune(' ')
}
}
return buffer.String()
}
func binstr2u64(s string) uint64 {
s = strings.Replace(s, " ", "", -1)
val, err := strconv.ParseUint(s, 2, 64)
if err != nil {
panic(err)
}
return val
}
func binstr2u8(s string) uint8 {
s = strings.Replace(s, " ", "", -1)
val, err := strconv.ParseUint(s, 2, 8)
if err != nil {
panic(err)
}
return uint8(val)
}
func binstr2byte(s string) byte {
return byte(binstr2u8(s))
}