About me

About me


RSS feed

Printing binary digits in groups

8th December 2021

When debugging a Lisp program recently I needed to print and check 16-bit binary numbers. To make them easier to read I wanted to group the digits together in groups of four.

Before writing a program to do this I wondered whether format could do this automatically, and so checked my copy of Steele. I was pleased to see that the Common Lisp committee had already anticipated this application, and Guy Steele gives the exact example I was looking for (Guy L. Steele, Common Lisp the Language, Second Edition, page 585):

(format nil "~19,,' ,4B" #x1CE)
"0000 0001 1100 1110”

Unfortunately my copy of LispWorks behaved differently:

CL-USER 1 > (format nil "~19,,' ,4B" #x1CE)
"          111001110"

I tried several other variations. It works if you add the colon modifier provided there are no leading zeros:

CL-USER 2 > (format nil "~19,,' ,4:B" #xface)
"1111 1010 1100 1110"

but fails if there are leading zeros:

CL-USER 3 > (format nil "~19,,' ,4:B" #x01ce)
"        1 1100 1110"

If you specify zero as a padding character the leading zeros are printed, but not grouped into fours:

CL-USER 4 > (format nil "~19,'0,' ,4:B" #x01ce)
"000000001 1100 1110"

I checked the same examples on SBCL and it agrees with LispWorks.

A workaround

So how to solve the original requirement? The best I can do is the following kludge:

CL-USER 5 > (subseq (format nil "~,,' ,4:B" (+ #x10000 #x01ce)) 2)
"0000 0001 1100 1110"

Does anyone have a more satisfactory workaround?

blog comments powered by Disqus