Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

strconv.ParseInt fails if number starts with 0

I’m currently having issues parsing some numbers starting with 0 in Go.

fmt.Println(strconv.ParseInt("0491031", 0, 64))

0 strconv.ParseInt: parsing "0491031": invalid syntax

GoPlayground: https://go.dev/play/p/TAv7IEoyI8I

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think this is due to some base conversion error, but I don’t have ideas about how to fix it.
I’m getting this error parsing a 5GB+ csv file with gocsv, if you need more details.

>Solution :

Quoting from strconv.ParseInt()

If the base argument is 0, the true base is implied by the string’s prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.

You are passing 0 for base, so the base to parse in will be inferred from the string value, and since it starts with a '0' followed by a non '0', your number is interpreted as an octal (8) number, and the digit 9 is invalid there.

Note that this would work:

fmt.Println(strconv.ParseInt("0431031", 0, 64))

And output (try it on the Go Playground):

143897 <nil>

(Octal 431031 equals 143897 decimal.)

If your input is in base 10, pass 10 for base:

fmt.Println(strconv.ParseInt("0491031", 10, 64))

Then output will be (try it on the Go Playground):

491031 <nil>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading