forked from tomatome/grdp
/
util.go
67 lines (59 loc) · 1.28 KB
/
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
package core
import (
"bytes"
"crypto/rand"
"encoding/binary"
"unicode/utf16"
)
func Reverse(s []byte) []byte {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
func Random(n int) []byte {
const alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = alpha[b%byte(len(alpha))]
}
return bytes
}
func UTF16ToLittleEndianBytes(u []uint16) []byte {
b := make([]byte, 2*len(u))
for index, value := range u {
binary.LittleEndian.PutUint16(b[index*2:], value)
}
return b
}
func LittleEndianBytesToUTF16(u []byte) []uint16 {
b := make([]uint16, 0, len(u)/2)
n := make([]byte, 2)
for i, v := range u {
if i%2 == 0 {
n[0] = v
} else {
n[1] = v
b = append(b, binary.LittleEndian.Uint16(n))
}
}
return b
}
// s.encode('utf-16le')
func UnicodeEncode(p string) []byte {
return UTF16ToLittleEndianBytes(utf16.Encode([]rune(p)))
}
func UnicodeDecode(p []byte) string {
r := bytes.NewReader(p)
n := make([]uint16, 0, 100)
for r.Len() > 0 {
a, _ := ReadUint16LE(r)
n = append(n, a)
}
//n := LittleEndianBytesToUTF16(p)
return string(utf16.Decode(n))
}
func BytesToUint64(b []byte) uint64 {
return binary.LittleEndian.Uint64(b)
}