"Robert Klemme" <shortcutter / googlemail.com> writes: > 2006/6/4, David Balmain <dbalmain.ml / gmail.com>: >> On 6/4/06, David Balmain <dbalmain.ml / gmail.com> wrote: >> To cast an Integer to a 32-bit signed integer you can use pack/unpack >> like Park said, or you could do it like this; >> >> def to_32_bit_signed(val) >> val |= -0x100000000 if (val & 0x80000000) > 0 >> val >> end > > And if you need this in multiple places of the program then it's > probably worth while to create a new subclass of Integer that > restricts itself to 32 bit calculations > > Int32 < Integer > def initialize(x) > @val = to_32(x) > end > def to_int ... > def coerce(a,b) ... > def hash() ... > def eql?(x) > def ==(x) ... > def +(x) ... > def -(x) ... > private > def to_32(x) ... > > end > > It's a nice excercise to get used to operators and numercial coercion. :-) > > Maybe we can even generalize that and put it into the standard lib - > something like a restricted integer that calculates with a max number > of bits. This is indeed a good Ruby exercise, but if it ever ends up in the standard library, I would then vote for it to be re-implemented in C, as the Ruby version would be hugely less efficient than the native 32-bit-integer operations that are already available in C. -- Lloyd Zusman ljz / asfast.com God bless you.