go - How can I convert from int to hex

ID : 131326

viewed : 10

Tags : gocastinggo

Top 5 Answer for go - How can I convert from int to hex

vote vote

90

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' 
vote vote

80

"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

vote vote

77

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
vote vote

70

Sprintf is more versatile but FormatInt is faster. Choose what is better for you

func Benchmark_sprintf(b *testing.B) { // 83.8 ns/op     for n := 0; n < b.N; n++ {         _ = fmt.Sprintf("%x", n)     } } func Benchmark_formatint(b *testing.B) { // 28.5 ns/op     bn := int64(b.N)     for n := int64(0); n < bn; n++ {         _ = strconv.FormatInt(n, 16)     } } 
vote vote

58

i := 4357640193405743614 h := fmt.Sprintf("%016x",i) fmt.Printf("Decimal: %d,\nHexa: %s", i, h)  # Result Decimal..: 4357640193405743614, Hexa.....: 3c7972ab0ae9f1fe 

Playground: https://play.golang.org/p/ndlMyBdQjmT

Top 3 video Explaining go - How can I convert from int to hex

Related QUESTION?