Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from an integer to its binary representation

Tags:

numeric

binary

go

Has anyone got an idea if there is any inbuilt functionality in Go for converting from any one of the numeric types to its binary number form.

For example, if 123 was the input, the string "1111011" would be the output.

like image 341
cobie Avatar asked Dec 14 '12 00:12

cobie


People also ask

What is the binary representation of the integer?

Binary numbers are usually represented with just two digits — 0 and 1 — cor- responding to the off and on states of the internal hardware. It takes quite a few more digits to represent a number in binary than in decimal, but any number that can be expressed in one can be converted to the other.


2 Answers

The strconv package has FormatInt, which accepts an int64 and lets you specify the base.

n := int64(123)  fmt.Println(strconv.FormatInt(n, 2)) // 1111011 

DEMO: http://play.golang.org/p/leGVAELMhv

http://golang.org/pkg/strconv/#FormatInt

func FormatInt(i int64, base int) string

FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

like image 105
I Hate Lazy Avatar answered Nov 05 '22 08:11

I Hate Lazy


See also the fmt package:

n := int64(123) fmt.Printf("%b", n)  // 1111011 
like image 44
Mark Avatar answered Nov 05 '22 09:11

Mark