Skip to content

Commit 84db903

Browse files
authored
Merge pull request #767 from devlights/add-binary-to-struct-example
2 parents 6212930 + 4a26bd5 commit 84db903

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# これは何?
2+
3+
C言語のようにバイト配列を構造体にキャストするサンプルです。
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# https://taskfile.dev
2+
3+
version: '3'
4+
5+
tasks:
6+
default:
7+
cmds:
8+
- go run main.go
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"encoding/binary"
6+
"encoding/hex"
7+
"fmt"
8+
"unsafe"
9+
)
10+
11+
type ST struct {
12+
V1 int32
13+
V2 uint32
14+
V3 [10]byte
15+
Dummy [6]byte
16+
}
17+
18+
func (me *ST) String() string {
19+
return fmt.Sprintf("V1=%d, V2=%d, V3=%s, Dummy=%v\n", me.V1, me.V2, string(me.V3[:]), me.Dummy)
20+
}
21+
22+
func main() {
23+
//
24+
// バイト列を作成
25+
//
26+
var (
27+
buf bytes.Buffer
28+
bin []byte
29+
)
30+
31+
binary.Write(&buf, binary.LittleEndian, int32(127))
32+
binary.Write(&buf, binary.LittleEndian, uint32(255))
33+
buf.WriteString("helloworld")
34+
buf.Write(make([]byte, 6))
35+
36+
bin = buf.Bytes()
37+
fmt.Println(hex.Dump(bin))
38+
39+
//
40+
// 構造体にキャスト
41+
//
42+
var (
43+
ptr unsafe.Pointer
44+
st *ST
45+
)
46+
47+
ptr = unsafe.Pointer(&bin[0])
48+
st = (*ST)(ptr)
49+
50+
fmt.Printf("%v\n", st)
51+
52+
/*
53+
00000000 7f 00 00 00 ff 00 00 00 68 65 6c 6c 6f 77 6f 72 |........hellowor|
54+
00000010 6c 64 00 00 00 00 00 00 |ld......|
55+
56+
V1=127, V2=255, V3=helloworld, Dummy=[0 0 0 0 0 0]
57+
*/
58+
59+
}

0 commit comments

Comments
 (0)