Considering that you need to divide the number by 2 until it equals 1, and rearrange the remains, how could this conversion be done in LISP?
Considering that you need to divide the number by 2 until it equals 1, and rearrange the remains, how could this conversion be done in LISP?
Assuming this is an exercise that needs to follow the reasoning of the statement, here are two examples from :
(defun dtb (x &optional (callback #'princ))
(unless (= x 0)
(dtb (floor x 2) callback)
(funcall callback (mod x 2))))
and
(defun dtb-collect (x)
(declare (type fixnum x))
(do ((x x (floor x 2))
(list nil (cons (mod x 2) list)))
((= x 0) list)))
See @AnthonyAccioly comment if you do not need the loop as described in the question body:
"If this is the case, in Common Lisp you just need to use the format function": (
format t "~B~%" 42
)="101010"
Link demo, also kindly provided by Anthony: link
One way to convert a number to binary is to be using the format ( as quoted in the AnthonyAccioly ) that is comparable to the printf of C .
(format t "~{~&~B~}" '(1 2 10 42 11)) ; 1 2 10 42 11 são os números a converter
The ~B
is similar to ~D
, but prints on binary basis (base 2 ) instead of decimal.