I have a 32bit unsigned integer and I want to divide it in 3 uint16 values. I want first 15bits, then 2 bits and then last 15 bits.
I am trying something like -
val >> 17
val >> 2
val >> 15
apart from first value, other 2 are not right and I know that but now able to figure out how to fix that?
For example,
package main
import "fmt"
func decode(bits uint32) (uint16, uint16, uint16) {
// first 15bits, then 2 bits and then last 15 bits.
const mask2 = ^uint32(0) >> (32 - 2)
const mask15 = ^uint32(0) >> (32 - 15)
b1 := uint16(bits >> (32 - 15))
b2 := uint16(bits >> (32 - 15 - 2) & mask2)
b3 := uint16(bits & mask15)
return b1, b2, b3
}
func main() {
b := uint32(4628440)
b1, b2, b3 := decode(b)
fmt.Printf("%032b %015b %02b %015b
", b, b1, b2, b3)
fmt.Printf("%d %d-%d-%d
", b, b1, b2, b3)
}
Output:
00000000010001101001111111011000 000000000100011 01 001111111011000
4628440 35-1-8152
A helper function to extract a range of bits makes this easy to understand (and test).
package main
import "fmt"
// extractUint16 extracts n bits of a from the given offset.
func extractUint16(a uint32, offset, n uint) uint16 {
return uint16((a >> offset) & (1<<n - 1))
}
func main() {
input := uint32(4628440)
a := extractUint16(input, 17, 15)
b := extractUint16(input, 15, 2)
c := extractUint16(input, 0, 15)
fmt.Println(a, b, c)
}