Skip to content

Instantly share code, notes, and snippets.

@DQNEO
Created September 11, 2021 13:20
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 DQNEO/30d2d8ba2d5a859e00c52e2a800c63c1 to your computer and use it in GitHub Desktop.
Save DQNEO/30d2d8ba2d5a859e00c52e2a800c63c1 to your computer and use it in GitHub Desktop.
Write a variable data as binary
package main
import (
"fmt"
"reflect"
"unsafe"
)
type Elf64_Ehdr struct {
e_ident [16]uint8
e_type uint16
e_machine uint16
e_ehsize uint16
e_phentsize uint16
e_phnum uint16
e_shentsize uint16
e_shnum uint16
e_shstrndx uint16
}
func main() {
//p := &Elf64_Ehdr{
// e_ident: [16]uint8{1,2,3},
// e_shstrndx: 4,
//}
var i int = 1
var p *int = &i
buf := ((*[unsafe.Sizeof(*p)]byte)(unsafe.Pointer(p)))[:]
buf2 := toBuf(p)
fmt.Printf("buf1=% x\n", buf)
fmt.Printf("buf2=% x\n", buf2)
}
func toBuf(ifc interface{}) []byte {
size := reflect.TypeOf(ifc).Elem().Size()
addr := reflect.ValueOf(ifc).Pointer()
type Slice struct {
addr uintptr
len uintptr
cap uintptr
}
slice := Slice{
addr: addr,
len: size,
cap: size,
}
pbuf := (*[]byte)(unsafe.Pointer(&slice))
return *pbuf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment