Thursday, May 21, 2015

processing the Hexidecimal prefix in Go

This is not considered expert level code or insight but I happened upon this today and wanted to document it for myself.

The strconv.Atoi() is essentially a macro to the ParseInt() method where the base is assigned 10. Therefore if you try to Atoi() a string with the hex prefix it will throw an error. The hex prefix is only a hint for the parser and only applies when the parser does not know the base. Hence when the base is ZERO.
package main
import ( 
    "fmt" 
    "strconv"
)
func main() {
    x, _ := strconv.Atoi("0x12") 
    fmt.Println("returns 0 because the base is implied to be 10:", x) 
    y, _ := strconv.ParseInt("0x12", 0, 0) 
    fmt.Println("returns the proper value:", y)
}
UPDATE: I should have read this link before posting. While there is nothing wrong with this code there is a level of improvement in my project.  I should use "\x12" in my project.  That will meet my needs without any other distractions or conversions since my next step would have been to convert the int into a rune or byte.

No comments:

Post a Comment

Fire OS and Android

The relationship between Amazon's FireOS and Google's Android OS is probably very complicated. And while there is probably some very...