-
Notifications
You must be signed in to change notification settings - Fork 0
/
byte.go
74 lines (70 loc) · 1.11 KB
/
byte.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
package tox
import "strconv"
func ToByte(v interface{}) byte {
switch v := v.(type) {
case byte:
return v
case int:
return byte(v)
case int8:
return byte(v)
case int16:
return byte(v)
case int32:
return byte(v)
case int64:
return byte(v)
case uint:
return byte(v)
case uint16:
return byte(v)
case uint32:
return byte(v)
case uint64:
return byte(v)
case float32:
return byte(v)
case float64:
return byte(v)
case string:
i, _ := strconv.Atoi(v)
return byte(i)
case bool:
if v {
return 1
}
return 0
default:
return 0
}
}
// ToByteArray converts bool, string, or byte arrays, if the conversion fails, it returns false.
func ToByteArray(v interface{}) []byte {
switch v := v.(type) {
case bool:
if v {
return []byte{0x01}
}
return []byte{0x00}
case nil:
return nil
case string:
return []byte(v)
case []byte:
return v
case []any:
rslt := make([]byte, len(v))
for i, v := range v {
rslt[i] = ToByte(v)
}
return rslt
default:
return nil
}
}
func TruncateByteArray(b []byte, length int) []byte {
if len(b) > length {
return b[:length]
}
return b
}