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")) }
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
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.
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) .
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With