The binary representation of unsigned integer in Go

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

The binary representation of unsigned integer in Go

问题

有没有内置的函数可以将uint转换为二进制整数的切片{0,1}

>> convert_to_binary(2)
[1, 0]
英文:

Is there a built-in function to convert a uint to a slice of binary integers {0,1} ?

>> convert_to_binary(2)
[1, 0]

答案1

得分: 2

我不知道有这样的函数,但是你可以使用strconv.FormatUint来实现这个功能。

示例(在play上):

func Bits(i uint64) []byte {
    bits := []byte{}

    for _, b := range strconv.FormatUint(i, 2) {
         bits = append(bits, byte(b - rune('0')))
    }

    return bits
}

FormatUint会将给定的uint转换为指定进制的字符串表示,这里是二进制。所以对于i=2,返回的字符串是"10"。在字节中,这表示为[49 48],因为1在ASCII和Unicode中表示为49,0表示为48。所以我们只需要遍历字符串,将每个字符(rune)减去48,并将其转换为字节即可。

英文:

I am not aware of such a function, however you can use strconv.FormatUint for that purpose.

Example (on play):

func Bits(i uint64) []byte {
    bits := []byte{}

    for _, b := range strconv.FormatUint(i, 2) {
         bits = append(bits, byte(b - rune('0')))
    }

    return bits
}

FormatUint will return the string representation of the given uint to a base, in this case 2, so we're encoding it in binary. So the returned string for i=2 looks like this: "10". In bytes this is [49 48] as 1 is 49 and 0 is 48 in ASCII and Unicode. So we just need to iterate over the string, subtracting 48 from each rune (unicode character) and converting it to a byte.

答案2

得分: 0

这是另一种方法:

package main

import (
   "bytes"
   "fmt"
   "math/bits"
)

func unsigned(x uint) []byte {
   b := make([]byte, bits.UintSize)
   for i := range b {
      if bits.LeadingZeros(x) == 0 {
         b[i] = 1
      }
      x = bits.RotateLeft(x, 1)
   }
   return b
}

func trimUnsigned(x uint) []byte {
   return bytes.TrimLeft(unsigned(x), string(0))
}

func main() {
   b := trimUnsigned(2)
   fmt.Println(b) // [1 0]
}

https://golang.org/pkg/math/bits#LeadingZeros

英文:

Here is another method:

package main

import (
   "bytes"
   "fmt"
   "math/bits"
)

func unsigned(x uint) []byte {
   b := make([]byte, bits.UintSize)
   for i := range b {
      if bits.LeadingZeros(x) == 0 {
         b[i] = 1
      }
      x = bits.RotateLeft(x, 1)
   }
   return b
}

func trimUnsigned(x uint) []byte {
   return bytes.TrimLeft(unsigned(x), string(0))
}

func main() {
   b := trimUnsigned(2)
   fmt.Println(b) // [1 0]
}

https://golang.org/pkg/math/bits#LeadingZeros

huangapple
  • 本文由 发表于 2013年10月24日 07:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/19553878.html
匿名

发表评论

匿名网友

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

确定