Elisp: 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)

Select the code, then Alt+x eval-region.

[see Emacs: 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://ergoemacs.org/emacs/elisp_converting_hex_decimal.html'
Version 2020-02-17"
  (interactive )
  (let ($inputStr $tempStr $p1 $p2 )
    (if (region-active-p)
          (setq $p1 (region-beginning))
          (setq $p2 (region-end)))
          (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))))

Put $5 at https://www.patreon.com/xahlee , or goto paypal.com and pay to Xah@XahLee.org . Message me on XahLee discord, say so, ask me questions.
Or Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode

ELisp Examples

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples