Logo

Programming-Idioms

  • C++
  • JS
  • PHP
  • Dart
  • Python

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

s = format(x, 'b')
s = '{:b}'.format(x)
#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();
let s = x.toString(2);
$s = sprintf("%b", $x);
var s = x.toRadixString(2);
(: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...