Programming

(Common Lisp) Converting characters to integers

steloflute 2014. 10. 27. 23:30
http://lisptips.com/post/11312746879/converting-characters-to-integers

 

If you have the character #\7 and you want the integer 7, you might be tempted to use (parse-integer (string char)) or even this ASCII-oriented technique:

(- (char-int char) (char-int #\0))

While the former is specified to give the right answer, the latter will only work by coincidence. The spec does discuss character ordering, but it makes no guarantees about the values returned by char-int or char-code.

What to use, then? digit-char-p not only returns a true value if its first argument represents a digit, the true value it returns is the integer value of that digit:

* (digit-char-p #\7)
7

It also works with other radixes:

* (digit-char-p #\a 16)
10

If the character is not a digit, digit-char-p returns nil.

 

 

'Programming' 카테고리의 다른 글

Smashing The Stack For Fun And Profit  (0) 2014.11.07
emacs tags 사용법  (0) 2014.10.31
Test EOF in Common Lisp  (0) 2014.10.24
Precise Garbage Collection for C  (0) 2014.10.01
setf macro in Common Lisp  (0) 2014.09.29