Skip to main content

digit-char

digit-char Function

Syntax:

digit-char weight &optional radix → char

Arguments and Values:

weight—a non-negative integer .

radix—a radix . The default is 10.

char—a character or false.

Description:

If weight is less than radix, digit-char returns a character which has that weight when considered as a digit in the specified radix. If the resulting character is to be an alphabetic1 character , it will be an uppercase character .

If weight is greater than or equal to radix, digit-char returns false.

Examples:

(digit-char 0) → #\0 
(digit-char 10 11) → #\A
(digit-char 10 10) → false
(digit-char 7) → #\7
(digit-char 12) → false
(digit-char 12 16) → #\C ;not #\c
(digit-char 6 2) → false
(digit-char 1 2) → #\1

See Also:

digit-char-p, graphic-char-p, Section 2.1 (Character Syntax)

Notes:

Expanded Reference: digit-char

Basic decimal digit conversion

digit-char converts a digit weight (0-9) to its corresponding character in the given radix (default 10).

(digit-char 0)
=> #\0
(digit-char 5)
=> #\5
(digit-char 9)
=> #\9

Hexadecimal digit conversion

When the radix is 16, weights 10-15 produce uppercase letters A-F.

(digit-char 10 16)
=> #\A
(digit-char 11 16)
=> #\B
(digit-char 15 16)
=> #\F
(digit-char 12 16)
=> #\C

Weight out of range returns NIL

If the weight is greater than or equal to the radix, digit-char returns NIL.

(digit-char 10 10)
=> NIL
(digit-char 12)
=> NIL
(digit-char 6 2)
=> NIL
(digit-char 2 2)
=> NIL

Binary digits

(digit-char 0 2)
=> #\0
(digit-char 1 2)
=> #\1

Converting a number to a digit string in any base

digit-char is useful for building string representations of numbers in arbitrary bases.

(defun integer-to-base-string (n base)
(if (zerop n)
"0"
(let ((digits '()))
(loop while (plusp n)
do (push (digit-char (mod n base) base) digits)
(setf n (floor n base)))
(coerce digits 'string))))

(integer-to-base-string 255 16)
=> "FF"
(integer-to-base-string 10 2)
=> "1010"
(integer-to-base-string 42 10)
=> "42"