Skip to content

Instantly share code, notes, and snippets.

@micheller
Created July 17, 2015 08:57
Show Gist options
  • Save micheller/4d3327357c976ffd33b9 to your computer and use it in GitHub Desktop.
Save micheller/4d3327357c976ffd33b9 to your computer and use it in GitHub Desktop.
My colleague asked me to write function written to convert selected binary constants (ex. 0b11101) to decimal view and back.
;; The fist version. Tricky and workarounded.
;; you can test it on this:
;; var BITS = ( 29, 0, 63, 85, 34 )
(defun bit-compact (start end)
(interactive "r")
(defun int-to-binary-string (i)
"convert an integer into it's binary representation in string format"
(let ((res ""))
(while (not (= i 0))
(setq res (concat (if (= 1 (logand i 1)) "1" "0") res))
(setq i (lsh i -1)))
(if (string= res "")
(setq res "0"))
res))
(defun format-bit (bit-string from-base)
"return either decimal string or python-style binary string"
(let ((number (string-to-number bit-string from-base)))
(cond ((= from-base 2) (int-to-string number))
((= from-base 10) (concat "0b" (int-to-binary-string number))))))
(defun do-convert (regex base)
"search for regexp and convert numbers: dec <-> binary"
(while (search-forward-regexp regex nil t)
(replace-match
(format-bit
(match-string 1)
base))))
(save-excursion
(if (not (use-region-p))
(progn (setq start (line-beginning-position)) (setq end (line-end-position))))
(goto-char start)
(narrow-to-region start end)
(cond ((> (how-many "0b[01]+" start end) 0) (do-convert "0b\\([01]+\\)" 2))
((> (how-many "[0-9]+" start end) 0) (do-convert "\\([0-9]+\\)" 10)))
(fill-region start end)
(widen)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment