minikomi
minikomi

Reputation: 8503

Converting from decimal to hex

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

Upvotes: 0

Views: 4048

Answers (1)

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

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)
}

Upvotes: 2

Related Questions