Search code examples
goendiannessuint16

calling uint16 on a rune is big or little endian?


I've got the following Go program:

package main

import (
    "fmt"
)

func main() {
    r := rune(249)
    x := uint16(r)
    fmt.Println(x)
}

If I have a rune r and call uint16(r) on it, is it going to be big or little endian encoded? Does Go default to one? Or does this depend on my hardware?


Solution

  • The rune type is an alias for int32, and the expression uint16(r) is a type conversion, which will retain the lowest 16 bits of the rune value. There is no encoding or serialization involved in here.

    Little endian or Big endian comes into play when you serialize values into a series of bytes, but that does not happen here.

    See this example:

    r := rune(0x0000fafa)
    fmt.Printf("%x\n", uint16(r))
    
    i := uint32(0xfffffafa)
    r = rune(i)
    fmt.Printf("%x\n", uint16(r))
    

    Output (try it on the Go Playground):

    fafa
    fafa