Home > Software engineering >  How to convert a slice of hexadecimal bytes to integer
How to convert a slice of hexadecimal bytes to integer

Time:10-08

I'm converting a base 10 integer to a hexadecimal string before storing it in a file:

str := fmt.Sprintf("x", 1662489944)

b, _ := hex.DecodeString(str)

file.Write(b) //seems to write 63179558

Yes I know this probably looks silly and I have no doubt there's better ways to do this: I wanted to pad this value with leading 0's.

When I read the contents of the file, I get a slice of bytes:

[]byte{63, 17, 95, 58}

How do I convert this slice back into the base 10 value of 1662489944 (32 bit)?

CodePudding user response:

It is not quite clear, how your actual hex-string is written to the file and read back. But based on one your comment,

When I run hexdump on the file, it shows 63 17 95 58

Which is evident enough that the byte slice you should be dealing with, should be in hex notation and not in decimal, i.e. []byte{0x63, 0x17, 0x95, 0x58} or in decimal byte slice []byte{99, 23, 149, 88}, but definitely not the one posted in OP. This can be confirmed by couple of methods in hex package, that encode hex string to bytes and vice-versa,

package main

import (
    "encoding/hex"
    "fmt"
    "log"
)

func main() {
    const s = "63179558"
    decoded, err := hex.DecodeString(s)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%v\n", decoded)
    fmt.Printf("%s\n", hex.EncodeToString([]byte{0x63, 0x17, 0x95, 0x58}))

}

which produces

[99 23 149 88]
63179558

confirming my above assumption.

As for your original question to convert the slice of hex bytes back to base 10, you could use the the encoding/binary package's implementation of ByteOrder, to convert to 32-bit, 64-bit numbers. So quite simply just

binary.BigEndian.Uint32([]byte{0x63, 0x17, 0x95, 0x58})

Go playground

CodePudding user response:

The following code writes the value to the file as a four byte big endian number.

str := fmt.Sprintf("x", 1662489944)
b, _ := hex.DecodeString(str)
file.Write(b)

Use this code to reverse the transformation:

b = make([]byte, 4)
io.ReadFull(file, b)
n := int(binary.BigEndian.Uint32(b))

PlayGround example.

Here's a more direct way to write the number to the file as a four byte big endian number.

b := make([]byte, 4)
binary.BigEndian.PutUint32(b, 1662489944)
file.Write(b)
  •  Tags:  
  • go
  • Related