Converting from decimal to hex

minikomi

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

Gareth McCaughan

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

converting hex to decimal with bash

converting string to hex, decimal, and octal

Converting from UIExtendedSRGBColorSpace to Hex

Python Converting hex string to decimal values

Python: converting single digit decimal to hex

Converting Decimal array to Hex array in Matlab

Converting a HEX value to DECimal value in C

How to escape from hex to decimal

Converting column to/from hex in PySpark

Converting from string to hex and subtracting

Converting from grades to gpa (with decimal)

Converting a 64 bit HEX to Decimal Floating-Pointt in Javascript

Converting Hex to Decimal and merging the result into one cell in matlab

Algorithm for converting large hex numbers into decimal form (base 10 form)

Matlab to Python; Converting a hex-address to a decimal numpy array

Signed decimal from a signed hex short in python

BASH base conversion from decimal to hex

Convert Hex to Decimal from char array

Converting a Hex String (from WPF TextBox) into byte

output converting from int to hex is not as expected, reason?

Python prevent readline from converting to hex value

SQL Select Converting to ASCII/varchar from Hex

Converting from Int to Hex in Delphi and Java

generate a hex file by converting strings into hex from a text file in Python

Converting a decimal number from str to float

Terraform - Issues Converting From Decimal To Percentage

Converting from decimal to base 4 using bitmasking

Java, converting from hexadecimal to decimal using casting

Converting from decimal to hexadecimal for ELROND blockchain