从十进制转换为十六进制

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

Converting from decimal to hex

问题

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

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {

	hexstring := fmt.Sprintf("%x", 12345678)
	fmt.Println(hexstring)
	hexbytes, _ := hex.DecodeString(hexstring)
	for {
		if len(hexbytes) >= 4 {
			break
		}
		hexbytes = append(hexbytes, 0)
	}
	fmt.Println(hexbytes)
}

我认为可以使用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.

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {

	hexstring := fmt.Sprintf("%x", 12345678)
	fmt.Println(hexstring)
	hexbytes, _ := hex.DecodeString(hexstring)
	for {
		if len(hexbytes) >= 4 {
			break
		}
		hexbytes = append(hexbytes, 0)
	}
	fmt.Println(hexbytes)
}

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)。类似这样:

package main

import (
"fmt"
"encoding/binary"
)

func main() {

    x := 12345678
    b := [4]byte{}
    binary.LittleEndian.PutUint32(b[:], uint32(x))
    fmt.Println(b)
}
英文:

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:

package main

import (
"fmt"
"encoding/binary"
)

func main() {

	x := 12345678
	b := [4]byte{}
	binary.LittleEndian.PutUint32(b[:], uint32(x))
	fmt.Println(b)
}

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:

确定