英文:
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
类型(实际上是它的子类型LittleEndian
和BigEndian
)。类似这样:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论