Logo

Programming-Idioms

  • Go
  • C++
  • Haskell

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

import Data.List
foldl (\acc -> (++ acc) . show) "" . unfoldr (\n -> if x == 0 then Nothing else Just (x `mod` 2, x `div` 2))

Sure, it will produce the empty string for 0 but it's a catamorphism composed with an anamorphism... I mean how much more Haskell-y do you get? There's even some currying and partial application in there!
import Numeric (showIntAtBase)
import Data.Char (intToDigit)
s x = showIntAtBase 2 intToDigit x ""
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.
#include <charconv>
std::string ToBinary(int x) {
  std::array<char, 64> buf;
  auto[ptr, ec] = std::to_chars(buf.data(), buf.data() + buf.size(), x, 2);
  auto s = std::string(buf.data(), ptr);
  return s;
}

The 2 at the end of to_chars is for base 2
#include <bitset>
std::bitset<sizeof(x)*8> y(x);
auto s = y.to_string();
(: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...