Go - convert string which represent binary number into int

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

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)
    }
}

Playground

Tags:

Go