convert a number from base 2 to base 10 in go

To convert a binary number to a decimal one in Go, you can use the strconv package which exposes the ParseInt function. This function can parse a string that represents a number in a given base, and convert it to an integer in base 10.

Here's an example code snippet that demonstrates how to convert a binary number to decimal:

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // binary number as a string
    binaryStr := "101011"

    // parsing the binary number as an int64 in base 2
    binaryInt, err := strconv.ParseInt(binaryStr, 2, 64)
    if err != nil {
        panic(err)
    }

    // printing the decimal representation
    fmt.Println(binaryInt)
}
354 chars
21 lines

In the example above, we define a binary number as a string, and then use strconv.ParseInt to parse it as an int64 in base 2. The third parameter of ParseInt specifies the base of the input string (in this case, 2 for binary). Finally, we print out the resulting decimal number.

gistlibby LogSnag