Skip to content

Instantly share code, notes, and snippets.

@alaindet
Created August 12, 2022 22:26
Show Gist options
  • Save alaindet/d0749323c2b3f1d4a27ffc7f27bb60c7 to your computer and use it in GitHub Desktop.
Save alaindet/d0749323c2b3f1d4a27ffc7f27bb60c7 to your computer and use it in GitHub Desktop.
[GO] Binary string to decimal converter
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