tags:

views:

70

answers:

2

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)
+4  A: 

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
A: 

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