4
Taking into account that it is necessary to divide the number by 2 until it is equal to 1, and to reorganize the remains, how this conversion could be made into LISP?
4
Taking into account that it is necessary to divide the number by 2 until it is equal to 1, and to reorganize the remains, how this conversion could be made into LISP?
4
Assuming it is an exercise that needs to follow the reasoning of the statement, follow two examples taken of this page:
(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 comment from @Anthonyaccioly if you do not need the loop as described in the body of the question:
"If this is the case, in Common Lisp just use the format function": (
format t "~B~%" 42
) = "101010"
Demonstrative link, also kindly provided by Anthony: http://ideone.com/WWg18G
Hi Bacco, leave it there, the comment is self-contained hehehe. Just an example to complement the idea link to the Ideone.
3
One way to convert a number into binary is to be using the function format(as quoted in the commentary of Anthonyaccioly) which is comparable to 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.
Browser other questions tagged lisp
You are not signed in. Login or sign up in order to post.
Hello user, I’m not sure about what you need, a whole is a whole indifferent to your representation. Usually we just want to format the number (in a string) on a given basis. If this is the case, in Common Lisp just use the function format -
(format nil "~B" 42) = "101010"
.– Anthony Accioly