英文:
getting bits out of a 32bit unsigned integer using bitshift in go lang
问题
我有一个32位无符号整数,我想将它分成3个uint16值。我想要前15位,然后2位,最后15位。
我尝试了以下代码:
val >> 17
val >> 2
val >> 15
除了第一个值之外,其他两个值都不正确,我知道这一点,但是我不知道如何修复它。
英文:
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?
答案1
得分: 4
例如,
package main
import "fmt"
func decode(bits uint32) (uint16, uint16, uint16) {
// 首先是前15位,然后是2位,最后是后15位。
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 001111111011000
4628440 35-1-8152
英文:
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\n", b, b1, b2, b3)
fmt.Printf("%d %d-%d-%d\n", b, b1, b2, b3)
}
Output:
00000000010001101001111111011000 000000000100011 01 001111111011000
4628440 35-1-8152
答案2
得分: 1
一个辅助函数用于提取一段位的代码,这样就容易理解(和测试)。
package main
import "fmt"
// extractUint16从给定的偏移量中提取a的n位。
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)
}
希望这对你有帮助!
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论