-
Notifications
You must be signed in to change notification settings - Fork 0
/
to_bytes_converters.go
119 lines (104 loc) · 2.01 KB
/
to_bytes_converters.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package faststrconv
const (
uint10 = 10
uint100 = 100
uint1000 = 1000
uint10000 = 10000
)
// Uint642Bytes converts an uint64 number to string.
func Uint642Bytes(num uint64) []byte {
convertedNumber := make([]byte, 20)
i := 19
for {
convertedNumber[i] = byte(num%10) | 0x30
num = num / 10
if num == 0 {
return convertedNumber[i:]
}
i--
}
}
// Uint322Bytes converts an uint32 number to string.
func Uint322Bytes(num uint32) []byte {
convertedNumber := make([]byte, 10)
i := 9
for {
convertedNumber[i] = byte(num%10) | 0x30
num = num / 10
if num == 0 {
return convertedNumber[i:]
}
i--
}
}
type unsigned interface {
~uint | ~uint32 | ~uint64
}
// Uint2Bytes converts an uint, uint32 and uint64 number to string.
func Uint2Bytes[UI unsigned](num UI) []byte {
var convertedNumber []byte
var i byte
if num > maxUint32 {
convertedNumber = make([]byte, 20)
i = 19
} else {
convertedNumber = make([]byte, 10)
i = 9
}
for {
convertedNumber[i] = byte(num%10) | 0x30
num = num / 10
if num == 0 {
return convertedNumber[i:]
}
i--
}
}
// Uint162Bytes converts an uint16 number to string.
func Uint162Bytes(num uint16) []byte {
convertedNumber, i := getSliceUint16(num)
for {
convertedNumber[i] = byte(num%10) | 0x30
num = num / 10
if i == 0 {
return convertedNumber
}
i--
}
}
func getSliceUint16(num uint16) ([]byte, int) {
if num < uint10 {
return make([]byte, 1), 0
}
if num < uint100 {
return make([]byte, 2), 1
}
if num < uint1000 {
return make([]byte, 3), 2
}
if num < uint10000 {
return make([]byte, 4), 3
}
return make([]byte, 5), 4
}
// Byte2Bytes converts a byte number to []byte.
func Byte2Bytes(num byte) []byte {
convertedNumber, i := getSliceByte(num)
for {
convertedNumber[i] = num%10 | 0x30
num = num / 10
if i == 0 {
return convertedNumber
}
i--
}
}
func getSliceByte(num byte) ([]byte, int) {
if num < uint10 {
return make([]byte, 1), 0
}
if num < uint100 {
return make([]byte, 2), 1
}
return make([]byte, 3), 2
}