Skip to content

Instantly share code, notes, and snippets.

@vaiorabbit
Created January 1, 2012 11:11
Show Gist options
  • Save vaiorabbit/1547035 to your computer and use it in GitHub Desktop.
Save vaiorabbit/1547035 to your computer and use it in GitHub Desktop.
dec2bin.el
; Example:
; * M-x dec2bin -> Decimal: 10 [Enter] -> 1010
; * (dec2bin 10) -> "1010"
; * C-u 10 M-x dec2bin -> 1010
; Ref.:
; * Basic syntax : http://xahlee.org/emacs/elisp_basics.html
; * concat : http://www.gnu.org/software/emacs/manual/html_node/elisp/Creating-Strings.html
; * called-interactively-p : http://www.gnu.org/software/emacs/manual/html_node/elisp/Distinguish-Interactive.html
(defun dec2bin (n)
"Returns binary expression of decimal number N."
(interactive "NDecimal: ")
(let (answer)
(setq answer "")
(if (= n 0)
(setq answer "0")
(let (log2n digit)
(setq log2n (floor (/ (log n) (log 2.0))))
(setq digit log2n)
(while (>= digit 0)
(let (place)
(setq place (expt 2 digit))
(setq answer (concat answer
(if (>= n place)
(progn (setq n (- n place)) "1")
"0")))
(setq digit (- digit 1))))))
(if (called-interactively-p 'any)
(message "%s" answer)
answer)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment