gotype-conversionbit-manipulationuint32uint16

Split uint32 into two uint16


How does one go about splitting a single uint32 var in Go into two uint16 vars, representing the 16 MSB and 16 LSB respectively?

Here is a representation of what I am trying to do:

var number uint32
var a uint16
var b uint16

number = 4206942069

Now how would one go about assigning the 16 MSB in number into a and the 16 LSB into b ?


Solution

  • Use the following code to assign the 16 most significant bits in number to a and the 16 least significant bits to b:

    a, b := uint16(number>>16), uint16(number)
    

    Run it on the playground.