海绵宝宝撒
例如,package mainimport "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\n", b, b1, b2, b3) fmt.Printf("%d %d-%d-%d\n", b, b1, b2, b3)}输出:00000000010001101001111111011000 000000000100011 01 0011111110110004628440 35-1-8152
胡说叔叔
提取一系列位的辅助函数使这易于理解(和测试)。package mainimport "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)}