Skip to content

Instantly share code, notes, and snippets.

@ruhtar
Created August 4, 2024 00:31
Show Gist options
  • Save ruhtar/f75fa07b07c0a67e03fa147383e60d9c to your computer and use it in GitHub Desktop.
Save ruhtar/f75fa07b07c0a67e03fa147383e60d9c to your computer and use it in GitHub Desktop.
[Golang] String to Int Parser without libs neither native functions
package main
import (
"fmt"
)
func main() {
result, err := toInt("431212")
if err != nil {
fmt.Println("deu erro moral")
}
fmt.Println(result)
}
func toInt(num string) (int, error) {
byteArray := []byte(num)
fmt.Println(byteArray)
result, err := byteArrayToInt(byteArray)
if err != nil {
return 0, err
}
return result, nil
}
func byteArrayToInt(byteArray []byte) (int, error) {
var result int
for _, charDigit := range byteArray {
var zeroInAscii byte = 48
decimalNumberValue := charDigit - zeroInAscii
result = result*10 + int(decimalNumberValue)
}
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment