Page 1 of 1

Binary operations in Lisp

Posted: Wed Nov 12, 2014 3:15 am
by rhjadhav
hello everyone. i am new to Lisp. i dont know how to perform binary operations in LISP?
can anyone share sample of code for binary addition or multiplication plz

Re: Binary operations in Lisp

Posted: Sat Nov 15, 2014 2:54 am
by Goheeca
A binary operation is treated as any other n-ary operation. There is nothing special about it. Use prefix notation:

Code: Select all

(+ 1 2) ; = 3
(* 2 3) ; = 6

Re: Binary operations in Lisp

Posted: Fri Nov 28, 2014 4:31 pm
by sylwester
Integers don't have base when they are stored. Your reader can read numbers in several different bases.

Code: Select all

(+ 10 #xa #b1010) ; ==> 30 
Now when makeing a string out of the number you get to choose the base:

Code: Select all

(let ((thirty (+ 10 #xa #b1010)))
  (format nil "~n ~x ~o ~b" thirty thirty thirty thirty))
; ==> "30 1E 36 11110"
There you have it. 30 displayed in 4 different bases. In CL you have the special variable *print-base* which sets the default base in which numbers are printed and *read-base* which sets the default base in which numbers are read when parsed:

Code: Select all

(let ((*print-base* 16)
        (*read-base* 2))
  (princ (read-from-string "1011"))) ; ==> B
Thats about all there is to know about displaying and parsing numbers. Now all your base are belong to you :-)

Re: Binary operations in Lisp

Posted: Tue Dec 02, 2014 6:09 am
by edgar-rft
I think the question was about binary operations (operations that take exactly two arguments), not how to compute numbers represented in binary format. And the question smells very much like homework...