从十进制转换为十六进制

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

Converting from decimal to hex

问题

我想将一个数字转换为十六进制,并将结果存储在一个长度为4的[]byte中。
这是我想到的方法,但感觉很绕。

  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. hexstring := fmt.Sprintf("%x", 12345678)
  8. fmt.Println(hexstring)
  9. hexbytes, _ := hex.DecodeString(hexstring)
  10. for {
  11. if len(hexbytes) >= 4 {
  12. break
  13. }
  14. hexbytes = append(hexbytes, 0)
  15. }
  16. fmt.Println(hexbytes)
  17. }

我认为可以使用make([]byte, 4)encoding/binary包来更好地完成这个任务,但我无法使其工作。

沙盒链接:http://play.golang.org/p/IDXCatYQXY

英文:

I want to convert a number to hex and store the result in a []byte up to length 4.
Here's what I came up with, but it feels very roundabout.

  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. hexstring := fmt.Sprintf("%x", 12345678)
  8. fmt.Println(hexstring)
  9. hexbytes, _ := hex.DecodeString(hexstring)
  10. for {
  11. if len(hexbytes) >= 4 {
  12. break
  13. }
  14. hexbytes = append(hexbytes, 0)
  15. }
  16. fmt.Println(hexbytes)
  17. }

I think there must be a better way to do this using make([]byte, 4) and the encoding/binary package, but I couldn't get it to work.

Sandbox link: http://play.golang.org/p/IDXCatYQXY

答案1

得分: 2

除非我误解了你的问题,否则这与十六进制没有关系。你想要将一个32位整数视为4个字节,并将这些字节放入[]byte中。

为此,你需要encoding/binary包中的ByteOrder类型(实际上是它的子类型LittleEndianBigEndian)。类似这样:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/binary"
  5. )
  6. func main() {
  7. x := 12345678
  8. b := [4]byte{}
  9. binary.LittleEndian.PutUint32(b[:], uint32(x))
  10. fmt.Println(b)
  11. }
英文:

Unless I've misunderstood your question, it isn't really about hex at all. You want to take a 32-bit integer, treat it as 4 bytes, and put those bytes into a []byte.

For this, you want the ByteOrder type (actually, its subtypes LittleEndian and BigEndian) from the encoding/binary package. Something like this:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/binary"
  5. )
  6. func main() {
  7. x := 12345678
  8. b := [4]byte{}
  9. binary.LittleEndian.PutUint32(b[:], uint32(x))
  10. fmt.Println(b)
  11. }

huangapple
  • 本文由 发表于 2012年6月13日 20:38:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/11015001.html
匿名

发表评论

匿名网友

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

确定