[racket] Handling bits

From: Michael Coppola (coppola.mi at husky.neu.edu)
Date: Mon Jan 24 02:59:03 EST 2011

Hola Racketeers,

I'm writing a program that performs a lot of binary math, and I was
wondering if there were any established ways in the Racket language to
handle bits or just C-style binary arithmetic in general.  For instance,
the C language lets you store any arbitrary byte to a buffer and perform
whatever you want to it (like bitwise math), but data types in Racket
are so sharply defined that I'm having trouble doing what I need to in a
straightforward manner.  Right now, my solution is to keep a string of
bits (literal 1s and 0s in a string) and write functions to recure
through it (by means of substring and string-append), but this is a very
not-so-great solution.  I've been calling these "bit strings" throughout
my program.

Here's an example of one of my functions:

;; bw-and : String String -> String
;; Performs a bitwise AND on two bit strings.  Both strings must be of
the same length.
(define (bw-and str1 str2)
  (cond [(string=? str1 "") ""]
        [else (string-append
                (bitwise-and (string->number (substring str1 0 1))
                             (string->number (substring str2 0 1))))
               (bw-and (substring str1 1) (substring str2 1)))]))

...and would be called like:

> (bw-and "11110000" "00110011")

Again, not very elegant.  Plus, I have to write functions to actually
convert back and forth between ASCII strings (normal text) and bit
strings.  Are there any specific data types or just more suitable ways
of storing and handling bit strings?  Thank you in advance, good sirs
and madams

Michael Coppola

Posted on the users mailing list.