Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference

Binary Integer Numbers


XLISP provides the #b read-macro for binary numbers:

#b0    => 0       #b1000  => 8        #b100000  => 16
#b1    => 1       #b1001  => 9        #b100001  => 17
#b10   => 2       #b1010  => 10       #b100010  => 18
#b11   => 3       #b1011  => 11       #b100011  => 19
#b100  => 4       #b1100  => 12       #b100100  => 20
#b101  => 5       #b1101  => 13       #b100101  => 21
#b110  => 6       #b1110  => 14       #b100110  => 22
#b111  => 7       #b1111  => 15       #b100111  => 23

(bin-string integer [all])
integer - an integer expression
all - a boolean expression
returns - the integer in binary form as string

(defun bin-string (integer &optional all)
  (if (integerp integer)
      (let ((digits (or (dolist (bits '(16 32 64 128) nil)
                          (let ((fixnum (round (expt 2.0 (1- bits)))))
                            (and (plusp (1- fixnum))
                                 (minusp fixnum)
                                 (return bits))))
                        (error "integer limit not found")))
            (string ""))
        (dotimes (x digits)
          (let ((digit (logand (round (expt 2.0 x)) integer)))
            (setq string (strcat (if (zerop digit) "0" "1") string))))
        (format nil "~a" (if all string (string-left-trim "0" string))))
      (error "not an integer" integer)))

The 'bin-string' function converts the 'integer' argument into binary form and returns is as a string. If the optional 'all' argument is not given or NIL, leading zeros are not included in the string. If the optional 'all' argument is non-NIL, all digits of the internal representation of the 'integer' argument, including leading zeros, are contained in the string. This is useful for debugging integer overflow and bit-wise functions.

(bin integer [all])
integer - an integer expression
all - a boolean expression
prints - the integer in binary form
returns - the integer argument

(defun bin (integer &optional all)
  (if (integerp integer)
      (format t "#b~a~%" (bin-string integer all))
      (format t ";; not an integer~%"))
  integer)

The 'bin' function prints the 'integer' argument in binary form on the screen. Together with the #b read-macro this can be used for interactive binary computations.

> (bin 12345678)
#b101111000110000101001110
12345678

> (bin 12345678 :all)
#b00000000101111000110000101001110
12345678

> (bin 1.2345678)
;; not an integer
1.2345678

> (bin (logand #b1011 #b1101))
#b1001
9

  Back to top


Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference