[racket] Handling bits

From: Jos Koot (jos.koot at telefonica.net)
Date: Mon Jan 24 05:36:43 EST 2011

You can use positive exact integers with bitwise operations. Look for the
word 'bitwise' in the docs.
Use (number->string n 2) for display of the bitstring n. You may have to add
leading zero's when you want a specific number of bits to be shown.
Jos 

> -----Original Message-----
> From: users-bounces at racket-lang.org 
> [mailto:users-bounces at racket-lang.org] On Behalf Of Michael Coppola
> Sent: 24 January 2011 08:59
> To: users at racket-lang.org
> Subject: [racket] Handling bits
> 
> 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
>                (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



Posted on the users mailing list.