I wrote a stupid solution for this, any better recipe? As you can see lots of useless conversions there.
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(l-i-1))*number
}
return int(result)
}
func main() {
fmt.Println(conv("1001"))
}
You want the strconv.ParseInt
function, which converts from an arbitrary base, into 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)
}
}
For example, on 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)
}
Output:
13