Skip to content

Instantly share code, notes, and snippets.

@devlights
Created March 5, 2024 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devlights/dd86f3bde576a0a699b4c35523515e65 to your computer and use it in GitHub Desktop.
Save devlights/dd86f3bde576a0a699b4c35523515e65 to your computer and use it in GitHub Desktop.
[GO] C言語みたいにバイナリを構造体にキャスト
package main
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"unsafe"
)
type ST struct {
V1 int32
V2 uint32
V3 [10]byte
Dummy [6]byte
}
func main() {
var buf bytes.Buffer
binary.Write(&buf, binary.LittleEndian, int32(255))
binary.Write(&buf, binary.LittleEndian, uint32(127))
buf.WriteString("helloworld")
buf.Write(make([]byte, 6))
b := buf.Bytes()
fmt.Println(hex.Dump(b))
p := unsafe.Pointer(&b[0])
s := (*ST)(p)
fmt.Printf("%+v\n", s)
/*
00000000 ff 00 00 00 7f 00 00 00 68 65 6c 6c 6f 77 6f 72 |........hellowor|
00000010 6c 64 00 00 00 00 00 00 |ld......|
&{V1:255 V2:127 V3:[104 101 108 108 111 119 111 114 108 100] Dummy:[0 0 0 0 0 0]}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment