-
Notifications
You must be signed in to change notification settings - Fork 5
/
checksum.go
117 lines (96 loc) · 2.24 KB
/
checksum.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
109
110
111
112
113
114
115
116
117
package tcpip
import (
"encoding/binary"
"fmt"
"reflect"
"strconv"
)
func paddingZero(arr []byte) []byte {
padarr := append(arr, 0x00)
return padarr
}
func printByteArr(arr []byte) string {
var str string
for _, v := range arr {
//fmt.Printf("%#x ", v)
str += fmt.Sprintf("%x ", v)
}
return str
}
func sum3BytetoLength(arr []byte) uint64 {
length, _ := strconv.ParseUint(fmt.Sprintf("%x", arr), 16, 16)
return length
}
func sumByteArr(arr []byte) uint {
var sum uint
for i := 0; i < len(arr); i++ {
if i%2 == 0 {
sum += uint(binary.BigEndian.Uint16(arr[i:]))
}
}
//fmt.Printf("0x%x : %b\n", sum, sum)
return sum
}
func checktoByteArr(value interface{}) {
rv := reflect.ValueOf(value)
rt := rv.Type()
var arr []byte
for i := 0; i < rv.NumField(); i++ {
field := rt.Field(i)
b := rv.Field(i).Interface().([]byte)
arr = append(arr, b...)
fmt.Printf("%s : %x\n", field.Name, b)
}
}
// 各構造体のフィールドが持つbyteをflatな配列にする
func toByteArr(value interface{}) []byte {
rv := reflect.ValueOf(value)
//rt := rv.Type()
var arr []byte
for i := 0; i < rv.NumField(); i++ {
//field := rt.Field(i)
//fmt.Printf("%s\n", field.Name)
b := rv.Field(i).Interface().([]byte)
arr = append(arr, b...)
}
return arr
}
func toByteLen(value interface{}) uint16 {
rv := reflect.ValueOf(value)
var arr []byte
for i := 0; i < rv.NumField(); i++ {
b := rv.Field(i).Interface().([]byte)
arr = append(arr, b...)
}
return uint16(len(arr))
}
func UintTo2byte(data uint16) []byte {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, data)
return b
}
func UintTo3byte(data uint32) []byte {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, data)
return b[1:]
}
func UintTo4byte(data uint32) []byte {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, data)
return b
}
func checksum(sum uint) []byte {
// https://el.jibun.atmarkit.co.jp/hiro/2013/07/tcp-f933.html
// 22DA6 - 20000 + 2 = 2DA8となり、2DA8をビット反転
val := sum - (sum>>16)<<16 + (sum >> 16) ^ 0xffff
return UintTo2byte(uint16(val))
}
func SumbyteArr(arr []byte) uint {
return sumByteArr(arr)
}
func CalcChecksum(sum uint) []byte {
return checksum(sum)
}
func ToPacket(value interface{}) []byte {
return toByteArr(value)
}