Monday, October 07, 2013
Print bit representation of a signed integer in Common Lisp
So, how do you print the bits of a signed integer in Common Lisp? Easy enough:
(defun print-bits (n) (let ((*print-base* 2)) (print n) (values))) > (print-bits 10) 1010
(defun print-bits (n) (format t "~B" n) (values)) > (print-bits 10) 1010
But what happens if you try to print a negative number?
> (print-bits -10) -1010
Not exactly what we were looking for -- we were looking for the bit representation of this number in two's complement form, which is how logical operations treat integers in Common Lisp. So how do we print the bits in two's complement form? The trick is to use
ldb returns a non-negative integer with the exact bits that were contained in the given integer, be it positive or negative.
(defun print-bits (n size) (format t "~B" (ldb (byte size 0) n)) (values)) > (print-bits -10 8) 11110110 > (print-bits -1 16) 1111111111111111
size is the number of bits that we want to print. Note that you need to be careful about size since this will truncate the printed bits if integer can't be represented in
Bonus: How do you pad this binary representation to the given
size with zeroes on the left for positive numbers? (negative numbers are already padded)
(defun print-bits (n size) (format t (format nil "~~~D,'0B" size) (ldb (byte size 0) n)) (values)) > (print-bits 1 4) 0001 > (print-bits 1 8) 00000001 > (print-bits -1 16) 1111111111111111
Subscribe to Posts [Atom]