Golang string to int
January 2, 2017
The built in 'strconv
1' 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 here
4, 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)
}
Comments
References
1
2
3
4
Tags