Logo

Programming-Idioms

  • Kotlin
  • C++
  • Python
  • Rust
  • PHP
  • Scala
  • C
  • Pascal
  • Go

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

import "strconv"
s := strconv.FormatInt(x, 2)

Here x has the type int64.

For very big numbers, prefer the type *big.Int.
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.
#include <bitset>
std::bitset<sizeof(x)*8> y(x);
auto s = y.to_string();
#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
s = format(x, 'b')
s = '{:b}'.format(x)
let s = format!("{:b}", x);

Formatting lets you choose another representation (e.g., `b` for binary, `X` for hex in upper case and `?` for debug output).
let s = format!("{x:b}");
$s = sprintf("%b", $x);
val s = x.toString(2)
var Iter,n:integer;
[...]
  S := '';
  for Iter := 0 to n do
    s:= Char(Ord('0')+(x shr Iter) and 1) + S;   

n: Number of digits
uses StrUtils;
var
  _x: Integer;
  _s: String;
begin
  _s := IntToBin(_x,8*SizeOf(Integer));
end.

SizeOf() gives the nr of bytes that type Integer is wide.
(: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...