-1

I'm working on a processor simulator in golang (for educational purposes). I need a type for memory unit for addressing. It may contain either a slice of memory (memory type is []byte) or one or several registers (they have []uint32 type), must be readable and writable. So, is there an option to convert []uint32 to []byte? I know there's an unsafe module, but I'm not sure how exactly to do this conversion. In other words, I need something like reinterpret_cast in C++

I know memory unit can be an interface with different implementations for memory, single register and several register, but it's not so efficient. Making register a byte slice also decreases performance

1 Answers1

0

The unsafe.Slice function makes it more convenient to convert an arbitrary pointer to a slice of any type. You could even make a generic version to cast a slice of any type to bytes if you were so inclined:

func castToBytes[T any](s []T) []byte {
    if len(s) == 0 {
        return nil
    }

    size := unsafe.Sizeof(s[0])
    return unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), int(size)*len(s))
}
JimB
  • 104,193
  • 13
  • 262
  • 255