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:


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

  (let (inputStr tempStr p1 p2 )
      (re-search-backward "[^0-9A-Fa-fx#]" nil t)
      (setq p1 (point) )
      (re-search-forward "[^0-9A-Fa-fx#]" nil t)
      (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.

Emacs Text Transform Under Cursor

  1. elisp wrapper + Python Ruby …
  2. Toggle Letter Case
  3. Title Case
  4. Upcase Sentences
  5. Cycle Space Hyphen Underscore
  6. Escape Quotes
  7. Quote Lines
  8. Spaces to New Lines
  9. Change Brackets/Quotes
  10. Remove Accent Marks
  11. Convert Straight/Curly Quotes
  12. Convert English/Chinese Punctuations
  13. Color Conversion (RGB, HSL, HSV)
  14. Decimal to Hexadecimal
  15. Replace Greek Letter Names to Unicode
  16. Twitterfy Text
  17. Toggle line wrap
  18. Clean White Space

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp