Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - convert string which represent binary number into int

Tags:

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")) } 
like image 654
Tianran Shen Avatar asked Feb 14 '12 03:02

Tianran Shen


People also ask

How to convert an integer variable to a string in go?

Use strconv.FormatInt function to convert an integer variable to a string in Go. int64 to a decimal string var number int64 = 12 str := strconv.FormatInt(number, 10) fmt.Println(str) int, int32, int16, int8 to a decimal string

How to convert decimal to binary number in Golang?

We have 2 ways to convert Decimal to Binary number in Golang. Following are two ways Below program takes decimal input number from user console, stores it in variable decimal. Inbuilt Standard package strconv provides FormatInt function used to convert Decimal to Binary number.

How to convert int to string in Golang?

Use strconv.FormatInt function to convert an integer variable to a string in Go. To convert int to string you can also use strconv.Itoa which is equivalent to strconv.FormatInt (int64 (i), 10) .

How to convert a string to an integer in C++?

The ParseInt () a function can be used to convert the string into an integer value. This function accepts a string parameter, converts it into a corresponding int type based on a base parameter. s: The source string and may begin with a leading sign: “+” or “-“. bitSize: This argument specifies the integer type (0 to 64).


1 Answers

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

like image 135
Lily Ballard Avatar answered Sep 27 '22 21:09

Lily Ballard