17.5.5.1 Bit-Counting

Calc does not include a built-in function for counting the number of “one” bits in a binary integer. It’s easy to invent one using b u to convert the integer to a set, and V # to count the elements of that set; let’s write a function that counts the bits without having to create an intermediate set.

(defmath bcount ((natnum n))
  (interactive 1 "bcnt")
  (let ((count 0))
    (while (> n 0)
      (if (oddp n)
          (setq count (1+ count)))
      (setq n (ash n -1)))
    count))

When this is expanded by defmath, it will become the following Emacs Lisp function:

(defun calcFunc-bcount (n)
  (setq n (math-check-natnum n))
  (let ((count 0))
    (while (math-posp n)
      (if (math-oddp n)
          (setq count (math-add count 1)))
      (setq n (calcFunc-lsh n -1)))
    count))