How can I convert from int to hex

If formatting some bytes, hex needs a 2 digits representation, with leading 0.

For exemple: 1 => '01', 15 => '0f', etc.

It is possible to force Sprintf to respect this :

h:= fmt.Sprintf("%02x", 14)
fmt.Println(h) // 0e
h2:= fmt.Sprintf("%02x", 231)
fmt.Println(h2) // e7

The pattern "%02x" means:

  • '0' force using zeros
  • '2' set the output size as two charactes
  • 'x' to convert in hexadecimal

Since hex is a Integer literal, you can ask the fmt package for a string representation of that integer, using fmt.Sprintf(), and the %x or %X format.
See playground

i := 255
h := fmt.Sprintf("%x", i)
fmt.Printf("Hex conv of '%d' is '%s'\n", i, h)
h = fmt.Sprintf("%X", i)
fmt.Printf("HEX conv of '%d' is '%s'\n", i, h)

Output:

Hex conv of '255' is 'ff'
HEX conv of '255' is 'FF'

"Hex" isn't a real thing. You can use a hexadecimal representation of a number, but there's no difference between 0xFF and 255. More info on that can be found in the docs which point out you can use 0xff to define an integer constant 255! As you mention, if you're trying to find the hexadecimal representation of an integer you could use strconv

package main

import (
    "fmt"
    "strconv"
)

func main() {
    fmt.Println(strconv.FormatInt(255, 16))
    // gives "ff"
}

Try it in the playground

Tags:

Casting

Go