开发者

Convert decimal <-> hex

开发者 https://www.devze.com 2022-12-21 10:00 出处:网络
Given a list of decimal numbers, how can each number be converted to its equivalent hexadecimal value, and vice versa?

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开发者_StackOverflow FF 40 40 80)


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."


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


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 (^[)
0

精彩评论

暂无评论...
验证码 换一张
取 消