Skip to content

Instantly share code, notes, and snippets.

@katyo
Last active August 29, 2015 14:14
Show Gist options
  • Save katyo/8e51a9f2af8990c48fc3 to your computer and use it in GitHub Desktop.
Save katyo/8e51a9f2af8990c48fc3 to your computer and use it in GitHub Desktop.
(defun read-c-radix (s)
(let ((c (substring s 0 (min (length s) 1))))
(cond ((string= s "2") 2)
((string= c "b") 2)
((string= s "8") 8)
((string= c "o") 8)
((string= s "16") 16)
((string= c "h") 16)
((string= s "10") 10)
((string= c "d") 10))))
(defun parse-c-radix-number (s)
(let* ((m (string-match "^\\(0b\\([01]+\\)\\|0o?\\([0-7]+\\)\\|0x\\([0-9a-fA-F]+\\)\\|\\([1-9][0-9]*\\|0\\)\\)$" s))
(b (match-string 2 s))
(o (match-string 3 s))
(x (match-string 4 s))
(d (match-string 5 s)))
(cond ((stringp b) (string-to-number b 2))
((stringp o) (string-to-number o 8))
((stringp x) (string-to-number x 16))
((stringp d) (string-to-number d 10)))))
(defun format-c-radix-binary (n &optional x)
(concat
(if x "0b" "")
(let ((n1 (ash n -1)))
(if (> n1 0)
(format-c-radix-binary n1)
""))
(if (= (logand n 1) 1) "1" "0")))
(defun format-c-radix-number (n r)
(if ((= r 2) (format-c-radix-binary n 't))
((format (cond ((= r 8) "0%o")
((= r 16) "0x%x")
('t "%d"))
n))))
(defun convert-c-radix (radix)
"Changes radix of number at cursor."
(interactive
(list (completing-read
"Result radix: "
'("bin" "oct" "hex" "dec" "2" "8" "16" "10"))))
(let* ((r (read-c-radix radix))
(b (bounds-of-thing-at-point 'word))
(s (buffer-substring-no-properties (car b) (cdr b)))
(n (parse-c-radix-number s)))
(if (and (numberp n) (numberp r))
(save-excursion (delete-region (car b) (cdr b))
(insert (format-c-radix-number n r))))
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment