SmallInteger and machine word size

Klaus D. Witzel klaus.witzel at cobss.com
Tue Feb 19 15:25:14 UTC 2008


On Tue, 19 Feb 2008 15:42:07 +0100, Igor Stasenko wrote:

> On 19/02/2008, Klaus D. Witzel 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.

Then forget about C-land and enter beautiful Squeak-land :) The next thing  
you might also want to put into your ByteArray is perhaps a String, so  
here's the data-independent solution:

  | byteStream dataStream |
  byteStream := (ByteArray new: 10) writeStream.
  dataStream := DataStream on: byteStream.
  dataStream nextPut: SmallInteger maxVal + 1; close.
  "close not really needed for streams on arrays"
  byteStream contents inspect.
  dataStream := DataStream on: byteStream contents readStream.
  dataStream next inspect

No knowledge about digitLength, nor about digitAt* etc (which is  
*not*necessary* for you but for implementors of the Number hierarchy  
anyways).

/Klaus

> 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
>





More information about the Squeak-dev mailing list