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.
emacs-lisp
(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: