Logo

Programming-Idioms

  • Lisp
  • Go
  • JS
  • Pascal

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

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.
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
(defparameter x 13)
(defvar s)
(setf s (format nil "~B" x))

X and S are defined globally, contrary to the Lisp convention that globals wear earmuffs.
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.
let s = x.toString(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...