/
encoding.go
108 lines (84 loc) · 1.88 KB
/
encoding.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
package tool
import (
"bytes"
"strings"
"encoding/hex"
"encoding/base64"
)
var (
defaultEncoding = NewEncoding()
)
/**
* 编码
*
* @create 2022-4-17
* @author deatil
*/
type Encoding struct{}
// 构造函数
func NewEncoding() Encoding {
return Encoding{}
}
// Base64 编码
func (this Encoding) Base64Encode(src []byte) string {
return base64.StdEncoding.EncodeToString(src)
}
func Base64Encode(src []byte) string {
return defaultEncoding.Base64Encode(src)
}
// Base64 解码
func (this Encoding) Base64Decode(s string) ([]byte, error) {
return base64.StdEncoding.DecodeString(s)
}
func Base64Decode(s string) ([]byte, error) {
return defaultEncoding.Base64Decode(s)
}
// Hex 编码
func (this Encoding) HexEncode(src []byte) string {
return hex.EncodeToString(src)
}
func HexEncode(src []byte) string {
return defaultEncoding.HexEncode(src)
}
// Hex 解码
func (this Encoding) HexDecode(s string) ([]byte, error) {
return hex.DecodeString(s)
}
func HexDecode(s string) ([]byte, error) {
return defaultEncoding.HexDecode(s)
}
// 补码
func (this Encoding) HexPadding(text string, size int) string {
if size < 1 {
return text
}
n := len(text)
if n == size {
return text
}
if n < size {
return strings.Repeat("0", size-n) + text
}
return text[n-size:]
}
func HexPadding(text string, size int) string {
return defaultEncoding.HexPadding(text, size)
}
// BytesPadding
func (this Encoding) BytesPadding(text []byte, size int) []byte {
if size < 1 {
return text
}
n := len(text)
if n == size {
return text
}
if n < size {
r := bytes.Repeat([]byte("0"), size - n)
return append(r, text...)
}
return text[n-size:]
}
func BytesPadding(text []byte, size int) []byte {
return defaultEncoding.BytesPadding(text, size)
}