Lisp way to cyclize integer bits

Suppose I have an integer such as 109, 1101101 in binary format. How to sort the bits of this number, for example: [64, 32, 8, 4, 1]? What would be a good way to do this in lisp? Should I change the bit for the macro by adding a case, or should I just convert the integer to a bit vector or list?

+3
source share
3 answers

If you want to process only "units", then the cycle over all bits is inefficient if there are not many. This is what I would do in this case.

(defmacro do-bits ((var x) &rest body)
  "Evaluates [body] forms after binding [var] to each set bit in [x]"
  (let ((k (gensym)))
    `(do ((,k ,x (logand ,k (1- ,k))))
         ((= ,k 0))
       (let ((,var (logand ,k (- ,k))))
         ,@body))))

2- , , , - , , .

, ( )

+6

logbitp, . ,

(loop for i below (integer-length 109)
      collect (if (logbitp i 109) 1 0))

=> (1 0 1 1 0 1 1)
+5

, , , . , "zerop", , , .

(defun iterate-bits-of (x handler)
  (unless (zerop x)
    (and (funcall handler (logand x 1))
     (iterate-bits-of (ash x -1) handler))))

(iterate-bits-of
 #b1101101
 #'(lambda (x) (not (format t "bit ~b~&" x))))
;; bit 1
;; bit 0
;; bit 1
;; bit 1
;; bit 0
;; bit 1
;; bit 1

, "ash" , , , 6502.

0

All Articles