Elisp: Convert Decimal / Hexadecimal Numbers

By Xah Lee. Date: . Last updated: .

This page shows you how to use emacs to convert between Decimal and Hexadecimal, and shows you how to write a elisp function that displays the decimal value of a hex string under cursor in source code.

Manual Solutions

Using calc

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

Using Emacs Lisp

Another way is using elisp. Open a new file, then type the following:

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

Select the code, then Alt+x eval-regionAlt+x】. Or, put cursor at the end of the right parenthesis, then Alt+x eval-last-sexpCtrl+x Ctrl+e】.

To open a new file in ErgoEmacs, press 【Ctrl+n】. In GNU Emacs, Alt+x switch-to-bufferCtrl+x b】 then type a new name.

Solution by Emacs Lisp Function

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

(defun what-hexadecimal-value ()
  "Prints the decimal value of a hexadecimal string under cursor.
Samples of valid input:

  ffff
  0xffff
  #xffff
  FFFF
  0xFFFF
  #xFFFF

Test cases
  64*0xc8+#x12c 190*0x1f4+#x258
  100 200 300   400 500 600"
  (interactive )

  (let (inputStr tempStr p1 p2 )
    (save-excursion
      (search-backward-regexp "[^0-9A-Fa-fx#]" nil t)
      (forward-char)
      (setq p1 (point) )
      (re-search-forward "[^0-9A-Fa-fx#]" nil t)
      (backward-char)
      (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 "Hex %s is %d" tempStr (string-to-number tempStr 16 ) )
    ))

The code is very easy to understand.

The (save-excursion …) part gets the positions of the hex string's boundary, and store them in vars {p1, p2}.

Then, we store the string in “inputStr”.

Then, replace-regexp-in-string is used to remove the 0x or #x prefix that are used in some languages to indicate hex number.

Then, (string-to-number tempStr 16 ) is used to turn a hex string to decimal.

ƒ ♥ λ

Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs