22

Given a list of decimal numbers, how can each number be converted to its equivalent hexadecimal value, and vice versa?

For example:

(convert2hex 255 64 64); -> (FF 40 40)
(convert2dec FF 40 40); -> (255 64 64)

(convert2hex 255 64 64 255 64 64 128)
(convert2dec FF 40 40 FF 40 40 80)
  • 1
    Is this homework? What I would start by doing is understanding at a high level the algorithm for converting base ten to base sixteen, *before* trying to implement this in lisp. – Amir Afghani Mar 01 '10 at 19:53
  • 3
    Not homework. Emacs Lisp probably isn't on any school's radar? :-) I would imagine that the actual conversion ability might be somewhere in Emacs. If I just want a number converted, I can use Calc, for example. –  Mar 01 '10 at 20:23
  • I wrote lisp while i was in school. Calling Calc seems like overkill, the base conversion algo is not that bad. – Amir Afghani Mar 01 '10 at 21:02

3 Answers3

34

Number to Hex:

(format "%X" 255) ;; => "FF"

You can also zero-pad the value with:

(format "%03X" 255) ;; => "0FF"

Where the 0 is the character to use for padding and 3 is the number of spaces to pad.

Hex string to number

(string-to-number "FF" 16) ;; => 255

The 16 means "read as base-16."

haxney
  • 3,358
  • 4
  • 30
  • 31
18

If you just want to type a hexadecimal number into Emacs, there's no need to call string-to-number, just use the #x reader syntax:

#xFF
==> 255

You can also use #b for binary, #o for octal numbers, or #36r for base 36:

#b10011001
==> 153
#o777
==> 511
#36rHELLO
==> 29234652

See section 3.1 Integer Basics in the Emacs Lisp Manual

Gareth Rees
  • 64,967
  • 9
  • 133
  • 163
2

I was interested in converting octal chars to hex chars in a source file.

I wanted to query search and replace on the following text:

'\0'   -> "\\0", // Null
'\7'   -> "\\a", // Bell (^G)
'\b'   -> "\\b", // Backspace (^H)
'\13'  -> "\\v", // Vertical tab (^K)
'\33'  -> "\\e", // Escape (^[)

Here was the regular expression search and replace

C-M-%

'\\\([0-9]+\)'

RET

'\,(format "\\0x%04X" (string-to-number \1 8))'

RET

The result is:

'\0x0000' -> "\\0", // Null
'\0x0007' -> "\\a", // Bell (^G)
'\b'      -> "\\b", // Backspace (^H)
'\0x000B' -> "\\v", // Vertical tab (^K)
'\0x001B' -> "\\e", // Escape (^[)
ashawley
  • 4,195
  • 1
  • 27
  • 40