Emacs Lisp: Convert Hexadecimal to Decimal

By Xah Lee. Date: . Last updated: .

Decimal to Hexadecimal

To convert Decimal to Hexadecimal, just type the decimal number, then Alt+x eval-last-sexp

emacs prints result in Emacs: Messages Buffer


255 (#o377, #xff)

means 255 in hexadecimal is ff

Hexadecimal to Decimal

in the same way, type the hexadecimal but start with #x, then Alt+x eval-last-sexp

Emacs command to show the Hexadecimal in Decimal

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 2023-03-17"
  (let (xinput xtemp xp1 xp2)
    (if (region-active-p)
        (setq xp1 (region-beginning) xp2 (region-end))
          (skip-chars-backward "[:xdigit:]#x")
          (setq xp1 (point))
          (skip-chars-forward "[:xdigit:]#x")
          (setq xp2 (point)))))
    (setq xinput (buffer-substring-no-properties xp1 xp2))
    (let ((case-fold-search nil))
      (setq xtemp (replace-regexp-in-string "\\`0x" "" xinput)) ; C, Perl
      (setq xtemp (replace-regexp-in-string "\\`#x" "" xtemp)) ; elisp
      (setq xtemp (replace-regexp-in-string "\\`#" "" xtemp))  ; CSS
    (message "input 「%s」, Hexadecimal 「%s」 is 「%d」" xinput xtemp (string-to-number xtemp 16))))

Elisp Examples

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples