[racket] Coerce Number to uint32
When you say "the same value that it had before", I think you mean that
the 32-bit representation of the signed int is the same as the 32-bit
representation of the unsigned int. By they're different values (and
Racket represents the values differently).
The bitwise operations in Racket treat an exact integer as representing
a semi-infinite twos-complement number:
(arithmetic-shift 1 31) represents
0...010000000000000000000000000000000
(bitwise-not (arithmetic-shift 1 31)) represents
1...101111111111111111111111111111111
#xFFFFFFFF represents
0...011111111111111111111111111111111
(bitwise-and #xFFFFFFFF (bitwise-not (arithmetic-shift 1 31))) represents
0...001111111111111111111111111111111
The numbers that can be converted to `uint32' are the ones that
correspond to all 0s before the last 32 binary digits, while the ones
that can be converted to `int32' correspond to the ones that have the
same binary digit before the last 31 binary digits.
At Sat, 9 Jun 2012 08:52:16 -0400, Vincent K wrote:
> That worked, thank you so much! I'm curious though, why does that work? By all
> rights that seems to basically be a no-op, due to it ending up with the same value
> it had before. Am I missing something, or is this just how Racket works?
>
> On Jun 9, 2012, at 4:13 AM, Matthew Flatt <mflatt at cs.utah.edu> wrote:
>
> > At Sat, 9 Jun 2012 02:42:43 -0400, Vince Kuyatt wrote:
> >> While working on the Rhipmunk FFI, I ran into a definition called
> >> "NOT_GRABABLE_MASK", which as far as I can tell, is defined as:
> >> #define GRABABLE_MASK (1<<31)
> >> #define NOT_GRABABLE_MASK (~GRABABLE_MASK)
> >>
> >> The problem with this, is that when I do the same operations:
> >> (define GRABABLE_MASK (int->uint (arithmetic-shift 1 31)))
> >> (define NOT_GRABABLE_MASK (bitwise-not GRABABLE_MASK))
> >>
> >> I get an error thrown back at me when I use it in one of the Chipmunk
> >> functions:
> >> Scheme->C: expects argument of type <uint32>; given -2147483649
> >>
> >> How can I coerce the definitions of those two masks so that they will be a
> >> uint32 that I can pass to the Chipmunk API?
> >
> > I think you want
> >
> > (define (sint32->uint32 v)
> > (bitwise-and #xFFFFFFFF v))
> >