[racket] Handling bits
If your data is always a "string" over 0,1 then you can write like
this (which is similar to yours)
(define (bit-and b1 b2)
(if (char=? b1 #\0)
b1
b2))
(define (bitwise f str1 str2)
(for/fold ((res "")) ((b1 str1) (b2 str2))
(string-append res (string (f b1 b2)))))
(bitwise bit-and "11110000" "00110011")
On Mon, Jan 24, 2011 at 1:29 PM, Michael Coppola
<coppola.mi at husky.neu.edu> wrote:
> 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
>