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
      (re-search-backward "[^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.

Emacs Text Transform Under Cursor

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

Emacs Lisp

Misc