英文:
Unexpected Bit.Reverse() result
问题
在算法任务中,我需要反转位数。这是一个例子:
但是当我使用"math/bits"的"bits.Reverse32(9)"时,结果是不同的2415919104。
链接:https://play.golang.org/p/Lf6qlOTMTXz
英文:
In the algorithm task, I need to reverse the bits.
Here is the example:
But when I use "math/bits"
bits.Reverse32(9)
the result is different 2415919104.
The link: https://play.golang.org/p/Lf6qlOTMTXz
答案1
得分: 4
// Reverse32函数返回x的位顺序反转后的值。
func Reverse32(x uint32) uint32 {...}
例如:1234 变为:4321
你要找的是所有位的切换:
var u uint32 = 9
fmt.Printf("%#032b\n", u) // 0b00000000000000000000000000001001
n := u ^ 0xffff_ffff
fmt.Printf("%#032b\n", n) // 0b11111111111111111111111111110110
试一试 这个:
package main
import (
"fmt"
"math/bits"
)
func main() {
var u uint32 = 9
fmt.Printf("%#032b\n", u) // 0b00000000000000000000000000001001
n := u ^ 0xffff_ffff
fmt.Printf("%#032b\n", n) // 0b11111111111111111111111111110110
u = bits.Reverse32(u)
fmt.Printf("%#032b\n", u) // 0b10010000000000000000000000000000
}
英文:
> // Reverse32 returns the value of x with its bits in reversed order.
func Reverse32(x uint32) uint32 {...}
e.g.: 1234 became: 4321
What you are looking for is all bits toggle:
var u uint32 = 9
fmt.Printf("%#032b\n", u) // 0b00000000000000000000000000001001
n := u ^ 0xffff_ffff
fmt.Printf("%#032b\n", n) // 0b11111111111111111111111111110110
Try it:
package main
import (
"fmt"
"math/bits"
)
func main() {
var u uint32 = 9
fmt.Printf("%#032b\n", u) // 0b00000000000000000000000000001001
n := u ^ 0xffff_ffff
fmt.Printf("%#032b\n", n) // 0b11111111111111111111111111110110
u = bits.Reverse32(u)
fmt.Printf("%#032b\n", u) // 0b10010000000000000000000000000000
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论