Whenever you use the "2r0" format, the reader automatically converts it to
its base-10 Integer value. This transformation happens at the reader level
right now -- check out the 'matchNumber' method in LispReader.java for
details. So (as far as I can tell) this means that there is no standalone
binary representation for you to use; that is, there's no direct way back
from an Integer value to the value that you entered in your program. You
*could* do something with Integer/toBinaryString... but then you're slinging
around strings to represent bits, and that just feels dirty.

Are you sure you need to use bit representations instead of ints? Can you
not make do with the built in clojure bit-* functions and a bit-concat like
the one below?

(defn bits-in
  "Calculates the minimum number of bits that a given Integer occupies."
  [n]
  (inc (int (/ (Math/log n) (Math/log 2)))))

(defn bit-concat
  "Concatenates a collection of Integers at the bit level."
  [& coll]
  (letfn [(concat-fn
           [a b]
           (bit-or
            (bit-shift-left a (bits-in b)) b))]
    (reduce concat-fn coll)))

-Brendan

On Fri, Mar 12, 2010 at 2:26 PM, Scott <sbuck...@gmail.com> wrote:

> Two questions
>
> How do I write a function 'bit' that converts an integer to binary
> representation:
>
> (bit 0) -> 2r0
> (bit 1) -> 2r1
> (bit 2) -> 2r10
> (bit 3) -> 2r11
> .
> .
> .
>
> As well, as function 'bit-concat' with the following behavior:
>
> (bit-concat 2r1 2r00) -> 2r100
> (bit-concat 2r0 2r00) -> 2r000
> (bit-concat 2r011 2r1100) -> 2r0111100
> .
> .
> .
>
> I looked into formats, but everything defaults to integer
> representation.  I need to stay in binary representation.  Its for a
> genetic algorithm with grey coding.
>
> Thanks!
>
> Scott
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com<clojure%2bunsubscr...@googlegroups.com>
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to