Go - convert a string that represents a binary number to int

I wrote a stupid solution for this, the best recipe? As you can see a lot of useless conversions.

package main import ( "fmt" "strconv" "math" ) func conv(str string) int { l := len(str) result := 0.0 for i,n := range str { number,_ := strconv.Atof64(string(n)) result += math.Exp2(float64(li-1))*number } return int(result) } func main() { fmt.Println(conv("1001")) } 
+11
source share
2 answers

You need the strconv.ParseInt function, which converts from an arbitrary base to a given bit size.

 package main import ( "fmt" "strconv" ) func main() { if i, err := strconv.ParseInt("1001", 2, 64); err != nil { fmt.Println(err) } else { fmt.Println(i) } } 

Playground

+21
source

For example, in Go 1,

 package main import ( "fmt" "strconv" ) func main() { i, err := strconv.ParseInt("1101", 2, 64) if err != nil { fmt.Println(err) return } fmt.Println(i) } 

Conclusion:

 13 
+8
source

Source: https://habr.com/ru/post/908393/


All Articles