What I'm looking for is a way to explain/understand simply how SmallInteger are 
implemented. 

>> Two's complement is a platform representation of integers not (necessarily) 
>> a smalltalk one. The concept of negative numbers has nothing to do with the 
>> radix a number is expressed in.

Yes I learned that 
>> 
>> There are convenient extensions to the ByteArray protocol added by FFI which 
>> allow easy conversion though. I don't have time this second to list them, 
>> but will do so in a few hours.
> 
> That's true, but the internal implementation leaks out the bitAnd:
> bitOr: and other bit operations...

I want to explain two's complement then Smalltalk smallinteger


\section{Two's complement of a number}

....

Creating a two complement version of a number equals negating the number bits 
and adding one.
\begin{code}{Calculating two complement of 3}
3 bitString '0000000000000000000000000000011'
3 bitInvert bitString '1111111111111111111111111111100'
(3 bitInvert + 1) bitString '1111111111111111111111111111101'
-3 bitString '1111111111111111111111111111101'
\end{code}
....


\section{SmallIntegers in Smalltalk}
Smalltalk small integers uses a two's complement arithmetic on 31 bits.  
An N-bit two's-complement numeral system can represent every integer in the 
range $-1 * 2^{N-1}\ to\ 2^{N-1}-1$. So for 32 bits Smalltalk systems, small 
integers values are the range -1073741824 to  1073741823. Let's check that a 
bit (this is the occasion to say it). 


\begin{code}{}
2 raisedTo: 29 
        returns 536870912 

536870912 class
        returns SmallInteger

2 raisedTo: 30 
        returns 1073741824

1073741824 class
        returns LargePositiveInteger

-1073741824 class 
        returns SmallInteger

2 class maxVal 
        returns 1073741823

-1 * (2 raisedTo: (31-1)) 
        returns -1073741824
        
(2 raisedTo: 30) - 1
        returns 1073741823

Reply via email to