Golang : Convert long hexadecimal with strconv.ParseUint example
Just an example on how to convert a long hexadecimal input string into integer. Most hexadecimal can be handled easily by strconv.ParseInt(hexString, 16, 64)
function, but there are times when you will encounter a long hexadecimal and ParseInt()
function will not be able to process the long hexadecimal. It will return either -1 or some weird result.
In order to cater for the long hexadecimal, you need to use strconv.ParseUint()
instead of ParseInt()
.
Yup, just use uint64
type for returning the result.
Here you go!
package main
import (
"fmt"
"strconv"
"strings"
)
func hex2int(hexStr string) uint64 {
// remove 0x suffix if found in the input string
cleaned := strings.Replace(hexStr, "0x", "", -1)
// base 16 for hexadecimal
result, _ := strconv.ParseUint(cleaned, 16, 64)
return uint64(result)
}
func main() {
hexString := "0x75bcd15"
fmt.Println(hex2int(hexString))
longHexString := "0xffb969d28651e43c"
fmt.Println(hex2int(longHexString))
longHexString = "0xFFB969D28651E43C"
fmt.Println(hex2int(longHexString))
}
Output:
123456789
18426875703280657468
18426875703280657468
See also : Golang : Convert integer to binary, octal, hexadecimal and back to integer
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.9k Golang : How to reverse elements order in map ?
+4.8k Golang : How to determine if request or crawl is from Google robots
+4.9k Golang : Calculate diameter, circumference, area, sphere surface and volume
+7.4k Golang : Go as a script or running go with shebang/hashbang style
+6.2k Golang : Get final or effective URL with Request.URL example
+6.4k Swift : Convert (cast) String to Float
+3.8k Python : Delay with time.sleep() function example
+10.6k Golang : Covert map/slice/array to JSON or XML format
+24.1k Golang : How to check if a connection to database is still alive ?
+7.8k Golang : Load ASN1 encoded DSA public key PEM file example
+11k Golang : Read XML elements data with xml.CharData example
+8.7k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example