Convert a decimal number to binary in LISP language

4

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?

    
asked by anonymous 30.05.2014 / 20:28

2 answers

4

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

    
30.05.2014 / 20:42
3

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.

Ideone

    
30.05.2014 / 21:57