-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
100 lines (89 loc) · 1.8 KB
/
convert.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
package convert
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"github.com/xxjwxc/public/mylog"
"strconv"
"time"
)
type RawBytes []byte
func cloneBytes(b []byte) []byte {
if b == nil {
return nil
} else {
c := make([]byte, len(b))
copy(c, b)
return c
}
}
func AsString(src interface{}) string {
switch v := src.(type) {
case string:
return v
case []byte:
return string(v)
case int:
return strconv.Itoa(v)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 64)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case time.Time:
return time.Time.Format(v, "2006-01-02 15:04:05")
case bool:
return strconv.FormatBool(v)
default:
{
b, _ := json.Marshal(v)
return string(b)
}
}
return fmt.Sprintf("%v", src)
}
//编码二进制
func EncodeByte(data interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf)
err := enc.Encode(data)
if err != nil {
mylog.Error(err)
return nil, err
}
return buf.Bytes(), nil
}
//解码二进制
func DecodeByte(data []byte, to interface{}) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
return dec.Decode(to)
}
//byte转16进制字符串
func ByteToHex(data []byte) string {
buffer := new(bytes.Buffer)
for _, b := range data {
s := strconv.FormatInt(int64(b&0xff), 16)
if len(s) == 1 {
buffer.WriteString("0")
}
buffer.WriteString(s)
}
return buffer.String()
}
//16进制字符串转[]byte
func HexToBye(hex string) []byte {
length := len(hex) / 2
slice := make([]byte, length)
rs := []rune(hex)
for i := 0; i < length; i++ {
s := string(rs[i*2 : i*2+2])
value, _ := strconv.ParseInt(s, 16, 10)
slice[i] = byte(value & 0xFF)
}
return slice
}