Emacs Lisp: Convert Decimal/Hexadecimal

By Xah Lee. Date: . Last updated: .

Here's several ways to convert between Hexadecimal to Decimal in emacs.

Using calc

To type a hexadecimal number, type #, then type “16#aa” for the hexadecimal “aa”.

Using Emacs Lisp

Here's how to convert decimal to hexadecimal:

;; decimal to hex. Returns 「a」
(format "%x" 10)

Here's how to convert hexadecimal to decimal:

;; hexadecimal 「a」 to decimal. Returns 「10」.
(format "%d" #xa)

Evaluate Elisp Code

Emacs Lisp Command

Here's a elisp command that prints the decimal value of a hexadecimal string under cursor.

(defun xah-show-hexadecimal-value ()
  "Prints the decimal value of a hexadecimal string under cursor.

Samples of valid input:

  ffff → 65535
  0xffff → 65535
  #xffff → 65535
  FFFF → 65535
  0xFFFF → 65535
  #xFFFF → 65535

more test cases
  64*0xc8+#x12c 190*0x1f4+#x258
  100 200 300   400 500 600

URL `http://xahlee.info/emacs/emacs/elisp_converting_hex_decimal.html'
Version 2020-02-17"
  (interactive )
  (let ($inputStr $tempStr $p1 $p2 )
    (if (region-active-p)
        (progn
          (setq $p1 (region-beginning))
          (setq $p2 (region-end)))
      (progn
        (save-excursion
          (skip-chars-backward "0123456789abcdefABCDEF#x")
          (setq $p1 (point))
          (skip-chars-forward "0123456789abcdefABCDEF#x" )
          (setq $p2 (point)))))
    (setq $inputStr (buffer-substring-no-properties $p1 $p2))
    (let ((case-fold-search nil))
      (setq $tempStr (replace-regexp-in-string "\\`0x" "" $inputStr )) ; C, Perl, …
      (setq $tempStr (replace-regexp-in-string "\\`#x" "" $tempStr )) ; elisp …
      (setq $tempStr (replace-regexp-in-string "\\`#" "" $tempStr )) ; CSS …
      )
    (message "input 「%s」, Hexadecimal 「%s」 is 「%d」" $inputStr $tempStr (string-to-number $tempStr 16))))
ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Elisp Examples

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples

Misc