Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #76 Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> "1101"

import "fmt"
import "math/big"
s := fmt.Sprintf("%b", x)

x has the type *big.Int.

This works because *big.Int implements the fmt.Formatter interface.
import "strconv"
s := strconv.FormatInt(x, 2)

Here x has the type int64.

For very big numbers, prefer the type *big.Int.
(:require [clojure.pprint])
(defn s
  [x]
  (pprint/cl-format nil "~b" x))

Call s and pass an integer x to it and it will return your integer in base 2.

New implementation...