[racket] Handling bits

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Mon Jan 24 09:35:40 EST 2011

2011/1/24 Michael Coppola <coppola.mi at husky.neu.edu>:
> 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.

This will not solve everything, but if you need to read and write bits to
a file, then the PLaneT library bit-io is a possibility.

Documentation:
http://planet.racket-lang.org/package-source/soegaard/bit-io.plt/2/0/doc.txt

Usage example:
http://blog.scheme.dk/2006/04/reading-and-writing-bits-bit-ioplt.html

-- 
Jens Axel Søgaard



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
>               (number->string
>                (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")
> "00110000"
>>
>
> 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
>
> Regards,
> Michael Coppola
> _________________________________________________
>  For list-related administrative tasks:
>  http://lists.racket-lang.org/listinfo/users
>



-- 
--
Jens Axel Søgaard


Posted on the users mailing list.