意外的 Bit.Reverse() 结果

huangapple go评论101阅读模式
英文:

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:
意外的 Bit.Reverse() 结果

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
}

huangapple
  • 本文由 发表于 2021年6月6日 14:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/67856404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定