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

# bsh

The 'bsh' functio performs an 'binary shift' operation:

(bsh integer count)
  integer - an integer expression
  count - an integer expression
  returns - the number shifted by count

    (defun bsh (integer count)
      (or (integerp integer) (error "not an integer" integer))
      (or (integerp count)   (error "not an integer" count))
      (if (zerop count)
          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")))
                (list nil)
                (string "#b"))
            (dotimes (x digits)
              (let ((digit (logand (round (expt 2.0 x)) integer)))
                (push (if (zerop digit) "0" "1") list)))
            (dotimes (x digits)
              (let ((digit (if (< -1 count digits) (nth count list) "0")))
                (setq string (strcat string digit))
                (incf count)))
            (eval (read (make-string-input-stream string))))))

The 'bsh' function performs a binary shift operation on the 'integer' argument. The bits of the 'integer' argument is shifted to the left by 'count' positions if 'count' is positive, or to the right by 'count' positions if 'count' is negative. The missing bits are filled with zeros.

Examples:

    (bsh 16  1)  =>
    (bsh 16  0)  =>
    (bsh 16 -1)  =>

    (defun debug:bsh (integer count)
      (let ((shifted (bsh integer count)))
        (format t "integer: ~a~%" (bin-string integer :all))
        (format t "shifted: ~a~%" (bin-string shifted :all))
        shifted))

See Binary Integer Numbers for the 'bin-string' function.

Back to top

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