How can I convert from int to hex
Solution 1
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'
Solution 2
"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"
}
Solution 3
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
Solution 4
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)
}
}
Solution 5
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
![KiYugadgeter](https://i.stack.imgur.com/qBvCy.png?s=256&g=1)
KiYugadgeter
Updated on July 09, 2022Comments
-
KiYugadgeter almost 2 years
I want to convert from int to hex in Golang. In strconv, there is a method that converts strings to hex. Is there a similar method to get a hex string from an int?
-
bio over 4 yearsThis solution does not support the leading zeros though, isn't it? A pity because it's really straightforward.
-
Adam Smith over 4 years@bio you're right, but other solutions on this (four year old question) do support leading zeroes