Golang string to int

January 2, 2017

The built in 'strconv1' package contains a function named 'Atoi2' (ASCII to integer). Which is just a wrapper for the 'ParseInt3' function.

Background

A string is an array of continuous single bytes, eight bits per character. So the word 'text' would read the following as an bytes array.

Byte offset 0 1 2 3
ASCII character t e x t
Byte value 116 101 120 116

You can find the ASCII table here4, each byte value correspondents to a character.

Now let's say we have a string that contains the number 179355. It would take up 6 bytes, whilst it can easily be contained in a 4 byte, 32 bit integer.

Byte offset 0 1 2 3 4 5
ASCII character 1 7 9 3 5 5
Byte value 49 55 57 51 53 53

The function

The builtin way is achieved by importing the package 'strconv'.

package main
import (
	"fmt"
	"strconv"
)
func main() {
	StringWithNumber := "179355"
	Integer, _ := strconv.Atoi(StringWithNumber)
	fmt.Println("Number as type integer: ", Integer)
}

Read also

Go random uint8 and uint16
How to Create Linked Lists in Go
Embedding Files into Your Go Program
Implementing a TCP Client and Server in Go: A Ping Pong Example
Discovering Go: A Deep Dive into Google's Own Programming Language
Implementing rate limiters in the Echo framework
Comments
References
2
strconv package - strconv - Go Packages

https://pkg.go.dev/strconv#Atoi

cached copy
3
strconv package - strconv - Go Packages

https://pkg.go.dev/strconv#ParseInt

cached copy
4
Tags