Go: Bitfields and bit packing

If the goal is just to have a very small struct, you'd probably just do:

package main

import "fmt"

type my_chunk uint32

func (c my_chunk) A() uint16 {
  return uint16((c & 0xffff0000) >> 16) 
}

func (c *my_chunk) SetA(a uint16) {
  v := uint32(*c)
  *c = my_chunk((v & 0xffff) | (uint32(a) << 16))
}

func main() {
  x := my_chunk(123)
  x.SetA(12)
  fmt.Println(x.A())
}

With the current 6g/8g, you're looking at a function call with ~6 instructions for the getter, and with time such calls will probably be inlined.


"There are no current plans for struct bitfields in Go."

You could write a Go package to do this; no assembler is required.

Tags:

Bit Fields

Go