-
Notifications
You must be signed in to change notification settings - Fork 0
/
number.go
49 lines (43 loc) · 1.51 KB
/
number.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
package util
import (
"encoding/binary"
"unsafe"
)
func PackInt[T int32 | int16 | int8 | uint32 | uint16 | uint8](hightBitNumber T, lowBitNumnber T) (packedNumber uint64) {
packedNumber = uint64(hightBitNumber)<<32 | uint64(lowBitNumnber)
return packedNumber
}
func LittleToBigEndian[T int | uint64 | uint32 | uint16](littleEndian T) (result T) {
switch unsafe.Sizeof(littleEndian) {
case 2:
bigEndianBytes := make([]byte, 2)
binary.LittleEndian.PutUint16(bigEndianBytes, uint16(littleEndian))
result = T(binary.BigEndian.Uint16(bigEndianBytes))
case 4:
bigEndianBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bigEndianBytes, uint32(littleEndian))
result = T(binary.BigEndian.Uint32(bigEndianBytes))
case 8:
bigEndianBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bigEndianBytes, uint64(littleEndian))
result = T(binary.BigEndian.Uint64(bigEndianBytes))
}
return
}
func BigToLittleEndian[T int | uint64 | uint32 | uint16](bigEndian T) (result T) {
switch unsafe.Sizeof(bigEndian) {
case 2:
bigEndianBytes := make([]byte, 2)
binary.BigEndian.PutUint16(bigEndianBytes, uint16(bigEndian))
result = T(binary.LittleEndian.Uint16(bigEndianBytes))
case 4:
bigEndianBytes := make([]byte, 4)
binary.BigEndian.PutUint32(bigEndianBytes, uint32(bigEndian))
result = T(binary.LittleEndian.Uint32(bigEndianBytes))
case 8:
bigEndianBytes := make([]byte, 8)
binary.BigEndian.PutUint64(bigEndianBytes, uint64(bigEndian))
result = T(binary.LittleEndian.Uint64(bigEndianBytes))
}
return
}