Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #76 Binary digits from an integer

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

E.g. 13 -> "1101"

local s = {}

while x > 0 do
    local tmp = math.fmod(x,2)
    s[#s+1] = tmp
    x=(x-tmp)/2
end

s=table.concat(s)
(: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...