-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
53 lines (45 loc) · 1000 Bytes
/
utils.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
package main
import (
"encoding/binary"
"fmt"
"strings"
)
func sumByteArr(packet []byte) (sum uint) {
for i, _ := range packet {
if i%2 == 0 {
sum += uint(byteToUint16(packet[i:]))
}
}
return sum
}
func calcChecksum(packet []byte) []byte {
// まず16ビット毎に足す
sum := sumByteArr(packet)
// あふれた桁を足す
sum = (sum & 0xffff) + sum>>16
// 論理否定を取った値をbyteにして返す
return uint16ToByte(uint16(sum ^ 0xffff))
}
func printMacAddr(macddr [6]uint8) string {
var str string
for _, v := range macddr {
str += fmt.Sprintf("%x:", v)
}
return strings.TrimRight(str, ":")
}
func byteToUint16(b []byte) uint16 {
return binary.BigEndian.Uint16(b)
}
func byteToUint32(b []byte) uint32 {
return binary.BigEndian.Uint32(b)
}
func uint16ToByte(i uint16) []byte {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, i)
return b
}
func uint32ToByte(i uint32) []byte {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, i)
return b
}