Dong.Ge

左手代码 右手江湖

golang中struct和[]byte的相互转换

东哥's Avatar 2020-04-23

  1. 1、struct转化为[]byte,转换方法如下:
  2. 2、将[]byte转换为struct,转换方法如下

cp from web

1、struct转化为[]byte,转换方法如下:

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
import (
"fmt"
"unsafe"
)
type TestStructTobytes struct {
data int64
}
type SliceMock struct {
addr uintptr
len int
cap int
}

func main() {

var testStruct = &TestStructTobytes{100}
Len := unsafe.Sizeof(*testStruct)
testBytes := &SliceMock{
addr: uintptr(unsafe.Pointer(testStruct)),
cap: int(Len),
len: int(Len),
}
data := *(*[]byte)(unsafe.Pointer(testBytes))
fmt.Println("[]byte is : ", data)
}

2、将[]byte转换为struct,转换方法如下

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
import (
"fmt"
"unsafe"
)
type TestStructTobytes struct {
data int64
}
type SliceMock struct {
addr uintptr
len int
cap int
}

func main() {

var testStruct = &TestStructTobytes{100}
Len := unsafe.Sizeof(*testStruct)
testBytes := &SliceMock{
addr: uintptr(unsafe.Pointer(testStruct)),
cap: int(Len),
len: int(Len),
}
data := *(*[]byte)(unsafe.Pointer(testBytes))
fmt.Println("[]byte is : ", data)
var ptestStruct *TestStructTobytes = *(**TestStructTobytes)(unsafe.Pointer(&data))
fmt.Println("ptestStruct.data is : ", ptestStruct.data)
}
本文最后更新于 天前,文中所描述的信息可能已发生改变