-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbyte2struct.go
60 lines (58 loc) · 1.71 KB
/
byte2struct.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
package byte2struct
import (
"encoding/binary"
"fmt"
"reflect"
"strconv"
)
// ReadBinaryWithStart convert byte array to struct
func ReadBinaryWithStart(data []byte, s interface{}) error {
dataLen := len(data)
var structType reflect.Type
var structValue reflect.Value
if value, ok := s.(reflect.Value); ok {
structValue = value
structType = value.Type()
} else if reflect.TypeOf(s).Kind() == reflect.Ptr {
structType = reflect.TypeOf(s).Elem()
structValue = reflect.ValueOf(s).Elem()
} else {
return fmt.Errorf("unsupport type")
}
for index := 0; index < structType.NumField(); index++ {
fieldType := structType.Field(index)
fieldValue := structValue.Field(index)
start := fieldType.Tag.Get("start")
if start == "" {
continue
}
startInt, _ := strconv.Atoi(start)
endInt := startInt + int(fieldType.Type.Size())
if startInt > dataLen || endInt > dataLen {
return fmt.Errorf("start out of range")
}
selectData := data[startInt:endInt]
switch fieldType.Type.Kind() {
case reflect.Uint32:
ret := binary.LittleEndian.Uint32(selectData)
structValue.Field(index).Set(reflect.ValueOf(ret))
case reflect.Int32:
ret := binary.LittleEndian.Uint32(selectData)
structValue.Field(index).Set(reflect.ValueOf(int32(ret)))
case reflect.Int64:
ret := binary.LittleEndian.Uint64(selectData)
structValue.Field(index).Set(reflect.ValueOf(int64(ret)))
case reflect.Uint64:
ret := binary.LittleEndian.Uint64(selectData)
structValue.Field(index).Set(reflect.ValueOf(ret))
case reflect.Struct:
err := ReadBinaryWithStart(data[startInt:], fieldValue)
if err != nil {
return err
}
default:
return fmt.Errorf("unsupport type %s", fieldType.Type.Kind())
}
}
return nil
}