Issues creating instance of SmallInteger

Michael Haupt mhaupt at
Fri May 12 16:05:11 UTC 2006


On 5/12/06, Michel Calonne <Michel.Calonne at> wrote:
> "SmallIntegers can only be created by performing arithmetic"...
> If somebody can tell me why it isn't possible to create a SmallInteger like this, and give me a way to do it, I'd appreciate...

short answer: SmallIntegers aren't actually objects.

Long answer (of course I won't let you down): SmallIntegers are an
optimised representation for numbers in the range +-2^30 (I believe).
These numbers are used extremely often and deserve special attention.
This is actually a detail of how the VM is implemented to optimise
arithmetics and handling of such "small" numbers in general.

In Smalltalk, all objects are referred to by pointers. A pointer is a
32-bit word. What it refers to is a structure in memory, containing of
a header (32 bit) and some more words containing pointers to all the
instance members of the object in question.

Imagine what would happen if an ordinary number was represented in
that way. For a 32-bit integer, you'd have (1) the pointer, (2) the
header, and (3) the contents (i.e., the actual value of the number).
That's, simplified, at least 3*32 bits for representing 32 bits.
Doesn't make much sense.

So, there is this neat little trick of (mis)using the lowest bit of
every pointer to denote whether the pointer is an actual pointer or
not. If it is set to 0, it's a pointer. If it's set to 1, the
"pointer" actually represents an instance of SmallInteger; a so-called
immediate integer.

Of course that means that you've only got 31 bits available for
representing a two's complement number, but who uses larger numbers
anyway? ;-)

Doing arithmetics with such an object is very simple: shift away the
lowest bit, adjust the sign bit, and perform ordinary CPU-provided
arithmetic operations. Bingo. Should the result ever exceed the range,
a LargePositiveInteger (or corresponding instance) is created.

Hope that helps,


More information about the Squeak-dev mailing list