forked from PlatONnetwork/PlatON-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes_util.go
111 lines (99 loc) · 2.51 KB
/
bytes_util.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
package core
import (
"bytes"
"encoding/binary"
"errors"
"math"
"strconv"
)
func Int32ToBytes(n int32) []byte {
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, tmp)
return bytesBuffer.Bytes()
}
func BytesToInt32(b []byte) int32 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int32
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int32(tmp)
}
func Int64ToBytes(n int64) []byte {
tmp := int64(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, tmp)
return bytesBuffer.Bytes()
}
func BytesToInt64(b []byte) int64 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int64
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int64(tmp)
}
func Float32ToBytes(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
func BytesToFloat32(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
return math.Float32frombits(bits)
}
func Float64ToBytes(float float64) []byte {
bits := math.Float64bits(float)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, bits)
return bytes
}
func BytesToFloat64(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
return math.Float64frombits(bits)
}
func BoolToBytes(b bool) []byte {
buf := bytes.NewBuffer([]byte{})
binary.Write(buf, binary.BigEndian, b)
return buf.Bytes()
}
func BytesConverter(source []byte, t string) interface{} {
switch t {
case "int32":
return BytesToInt32(source)
case "int64":
return BytesToInt64(source)
case "float32":
return BytesToFloat32(source)
case "float64":
return BytesToFloat64(source)
case "string":
return string(source[:])
case "bool":
return bytes.Equal(source, []byte{1})
default:
return source
}
}
func StringConverter(source string, t string) ([]byte, error) {
switch t {
case "int32", "uint32", "uint", "int":
dest, err := strconv.Atoi(source)
return Int32ToBytes(int32(dest)), err
case "int64", "uint64":
dest, err := strconv.ParseInt(source, 10, 64)
return Int64ToBytes(dest), err
case "float32":
dest, err := strconv.ParseFloat(source, 32)
return Float32ToBytes(float32(dest)), err
case "float64":
dest, err := strconv.ParseFloat(source, 64)
return Float64ToBytes(dest), err
case "bool":
if "true" == source || "false" == source {
return BoolToBytes("true" == source), nil
} else {
return []byte{}, errors.New("invalid boolean param")
}
default:
return []byte(source), nil
}
}