Created
August 12, 2022 22:26
-
-
Save alaindet/d0749323c2b3f1d4a27ffc7f27bb60c7 to your computer and use it in GitHub Desktop.
[GO] Binary string to decimal converter
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() { | |
fmt.Println( | |
BinaryStringToDecimal("0110"), // 6 | |
BinaryStringToDecimal("0011"), // 3 | |
) | |
} | |
func BinaryStringToDecimal(bin string) int { | |
result := 0 | |
ii := len(bin) | |
pow := 1 | |
for i := 0; i < ii; i++ { | |
d := bin[ii-i-1] | |
n := 0 | |
if d == '1' { | |
n = 1 | |
} | |
result += pow * n | |
pow *= 2 | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment