how to convert hex to int in golang?
August 21, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert hex to int in golang, use the strings.Replace()
and strconv.ParseInt()
method it will convert your hex value to integer.
The strings.Replace()
use for Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.
The strconv.ParseInt()
interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows/
Today, I will show you how do I convert hex to int in golang, as mentioned above I’m going to use the strings.Replace()
and strconv.ParseInt()
method.
Let’s start our Golang convert hex to int example
main.go
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
hexaString := "23f"
numberStr := strings.Replace(hexaString, "0x", "", -1)
numberStr = strings.Replace(numberStr, "0X", "", -1)
output, err := strconv.ParseInt(numberStr, 16, 64)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Output %d", output)
}
In the above example, we have converted the hex value to a int and printed in golang console. let’s check the output.
Output
Output 575
I hope it helps you, All the best 👍.