Logo

Programming-Idioms

  • PHP
  • Python
  • Scheme
  • Pascal
  • JS
  • C#

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

String s = Convert.ToString(x,2);
String s = Convert.ToString(x,2).PadLeft(16, '0');

If you want some leading zeroes.
$s = sprintf("%b", $x);
s = '{:b}'.format(x)
s = format(x, 'b')
(define (binary-representation x)
  (let loop ([N x]
             [s '()])
    (let ([NN (arithmetic-shift N -1)])
      (cond [(zero? N) (list->string s)]
            [(odd? N) (loop NN (cons #\1 s))]
            [else (loop NN (cons #\0 s))]))))
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.
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...