SmallInteger and machine word size

Igor Stasenko siguctua at gmail.com
Tue Feb 19 14:42:07 UTC 2008


On 19/02/2008, Klaus D. Witzel <klaus.witzel at cobss.com> wrote:
> On Tue, 19 Feb 2008 14:13:09 +0100, Igor Stasenko wrote:
>
> > Hello,
> >
> > I want to use integer values to pass them over a binary data stream.
> > And for this i need to encode a smallinteger value into bytearray
> > (endianess not matters).
> > Is there any way how to do it in platform independent way?
>
> These are the requirements addressed by class InterpreterSimulator (and
> its superclass and subclasses) when it saves+restores its .image; you have
> the solutions in the VMMaker package.
>
> /Klaus

This is true, but not helps to write any code not related to VMMaker.
It's a generic problem:
 suppose you want to pass ANY integer value to binary stream.

Since smalltalkers care little, how integers are stored, i implemented
2 methods for encoding and decoding integer values from bytearray.

The only limitation of my method, is that it can't encode too large
integers (with number of bytes > 127 to store it).

encodeInt: anInteger
	| length bytes |

	length := anInteger digitLength.
	bytes := ByteArray new: length + 1.
	bytes at: 1 put: ( (length bitShift: 1) + (anInteger < 0 ifTrue: [1]
ifFalse: [0]) ).

	1 to: length do: [:i |
		bytes at: i+1 put: (anInteger digitAt: i)
	].

	^ bytes
----
decodeInt: aBytes offset: index
	| neg result length |

	length := aBytes at: index.
	neg := (length bitAnd: 1) = 1.
	length := length bitShift: -1.
	result := Integer new: length neg: neg.
	1 to: length do: [:i | result digitAt: i put: (aBytes at: index + i) ].

	^ result

-- 
Best regards,
Igor Stasenko AKA sig.



More information about the Squeak-dev mailing list