-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytearrays.go
72 lines (64 loc) · 1.75 KB
/
bytearrays.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
package bytearrays
import (
"bytes"
"math/big"
"reflect"
"unsafe"
)
func IntToByteArray(num int32) []byte {
// Get the size of the int in bytes
size := int(unsafe.Sizeof(num))
// Pre-fill a blank slice with null bytes to fit the int size
arr := make([]byte, size)
for i := 0; i < size; i++ {
// Convert the current byte in the int to a byte
// Formula: byte = pointer_of(ptr_to_int + curent_byte_offset)
byt := *(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&num)) + uintptr(i)))
// Append byte to slice
arr[i] = byt
}
return arr
}
func ByteArrayToInt(arr []byte) int32 {
// Pre-create an int32 to place bytes into
val := int32(0)
// Get the size of the byte array
size := len(arr)
for i := 0; i < size; i++ {
// Place the current byte within the int at the offset position
// Formula: pointer_of(ptr_to_int + curent_byte_offset) = byte
*(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&val)) + uintptr(i))) = arr[i]
}
return val
}
func ReverseAny(s interface{}) {
// Reflectively get the value of the slice size
n := reflect.ValueOf(s).Len()
// Create a swapper that will perform actions on the slice
swap := reflect.Swapper(s)
for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
// Swap each far-left value with the far-right value floor(len / 2) times
// Example:
// [1, 2, 3, 4, 5] <-- intitial
// [5, 2, 3, 4, 5] <-- 1st pass
// [5, 4, 3, 2, 5] <-- 2nd pass [DONE]
swap(i, j)
}
}
func TwosComplement(val int32) []byte {
n := big.NewInt(int64(val))
var r []byte
if n.Cmp(big.NewInt(0)) != -1 {
r = n.Bytes()
} else {
mask := big.NewInt(1)
mask.Lsh(mask, 64)
r = n.Add(n, mask).Bytes()
}
res := bytes.NewBuffer([]byte{})
for i := 0; i < 8-len(r); i++ {
res.WriteByte(0)
}
res.Write(r)
return res.Bytes()[4:8]
}