-
-
Notifications
You must be signed in to change notification settings - Fork 511
/
buffers.go
61 lines (48 loc) · 1.18 KB
/
buffers.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
package main
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"log"
"math/big"
"reflect"
)
func writeUIntBE(buffer []byte, value, offset, byteLength int64) {
slice := make([]byte, byteLength)
val := new(big.Int)
val.SetUint64(uint64(value))
valBytes := val.Bytes()
buf := bytes.NewBuffer(slice)
err := binary.Write(buf, binary.BigEndian, &valBytes)
if err != nil {
log.Fatal(err)
}
slice = buf.Bytes()
slice = slice[int64(len(slice))-byteLength : len(slice)]
copy(buffer[offset:], slice)
}
func writeUIntLE(buffer []byte, value, offset, byteLength int64) {
slice := make([]byte, byteLength)
val := new(big.Int)
val.SetUint64(uint64(value))
valBytes := val.Bytes()
tmp := make([]byte, len(valBytes))
for i := range valBytes {
tmp[i] = valBytes[len(valBytes)-1-i]
}
copy(slice, tmp)
copy(buffer[offset:], slice)
}
func main() {
buf := make([]byte, 6)
writeUIntBE(buf, 0x1234567890ab, 0, 6)
fmt.Println(hex.EncodeToString(buf))
buf2 := make([]byte, 6)
writeUIntLE(buf2, 0x1234567890ab, 0, 6)
fmt.Println(hex.EncodeToString(buf2))
isEqual := reflect.DeepEqual(buf, buf2)
fmt.Println(isEqual)
isEqual = reflect.DeepEqual(buf, buf)
fmt.Println(isEqual)
}