On Thu, Apr 1, 2010 at 12:29 AM, Armando Blancas
<armando_blan...@yahoo.com> wrote:
> But if numbers should default to positive but not be coerced to
> negative, e.g., a -189 just for (short -0xBD) this might work, using
> nil for out of range values:

Yeah, but I was assuming (insert standard caveat here) that the goal
is to treat the hex values as bit patterns and return whatever numeric
value Clojure requires to get the corresponding bit pattern, hence -1
for 0xffff, etc.

> I don't know if there's anything predefined, but you can always fall
> back to using (Short/MIN_VALUE), (Short/MAX_VALUE), etc.

Yeah, I was hoping for something predefined.  Failing that,  I used
the /SIZE field, and came up with the below. The fn name "unsigned"
might seem backwards (truncating-cast would be more descriptive), but
I called it that because it lets you use (unsigned byte 255) to mean
the same thing as (byte -1).

(defn box-type [s] (class (s 0)))

(defn bit-size [s] (eval (read-string (str (.getName (box-type s)) "/SIZE"))))

(defn unsigned [type value]
        (let [size (bit-size type)
              sign-bit (- size 1)
              negative-mask (bit-shift-left -1 size)
              positive-mask (- (bit-shift-left 1 size) 1)]
          (type
            (if (bit-test value sign-bit)
              (bit-or value negative-mask)
              (bit-and value positive-mask)))))
-- 
Mark J. Reed <markjr...@gmail.com>

-- 
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

To unsubscribe, reply using "remove me" as the subject.

Reply via email to