Created
August 4, 2024 00:31
-
-
Save ruhtar/f75fa07b07c0a67e03fa147383e60d9c to your computer and use it in GitHub Desktop.
[Golang] String to Int Parser without libs neither native functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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