-
Notifications
You must be signed in to change notification settings - Fork 3
/
int.go
98 lines (75 loc) · 1.62 KB
/
int.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
package util
import (
"bytes"
"encoding/binary"
"math"
)
func IntToBytes(i int) []byte {
b := new(bytes.Buffer)
_ = binary.Write(b, binary.LittleEndian, int64(i))
return b.Bytes()
}
func BytesToInt(b []byte) (int, error) {
i, err := BytesToInt64(b)
if err != nil {
return 0, err
}
return int(i), nil
}
func Int64ToBytes(i int64) []byte {
b := new(bytes.Buffer)
_ = binary.Write(b, binary.LittleEndian, i)
return b.Bytes()
}
func BytesToInt64(b []byte) (int64, error) {
var i int64
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &i)
if err != nil {
return 0, err
}
return i, nil
}
func UintToBytes(i uint) []byte {
b := new(bytes.Buffer)
_ = binary.Write(b, binary.LittleEndian, uint64(i))
return b.Bytes()
}
func BytesToUint8(b []byte) (uint8, error) {
var i uint8
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &i)
if err != nil {
return 0, err
}
return i, nil
}
func Uint8ToBytes(i uint8) []byte {
b := new(bytes.Buffer)
_ = binary.Write(b, binary.LittleEndian, i)
return b.Bytes()
}
func Uint64ToBytes(i uint64) []byte {
b := new(bytes.Buffer)
_ = binary.Write(b, binary.LittleEndian, i)
return b.Bytes()
}
func BytesToUint64(b []byte) (uint64, error) {
var i uint64
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &i)
if err != nil {
return 0, err
}
return i, nil
}
func Float64ToBytes(i float64) []byte {
bt := math.Float64bits(i)
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, bt)
return b
}
func BytesToFloat64(b []byte) float64 {
bt := binary.LittleEndian.Uint64(b)
return math.Float64frombits(bt)
}