Byte order and ByteArray conversions [SUMMARY]
David T. Lewis
lewis at mail.msen.com
Tue Nov 2 04:22:09 UTC 1999
On Sun, Oct 31, 1999 at 11:37:59AM -0500, David T. Lewis wrote:
>
> I'm sure I'm missing something obvious, but I'd like to be able to convert
> integers to and from byte arrays in native machine byte ordering, without
> resorting to a new primitive.
>
> 1) Does Squeak know the byte order convention of the hardware it's running
> on? I can't find any method to query for this.
>
> 2) Class ByteArray knows how to convert itself into integers, given that
> you can tell it the answer to question 1. Is there any existing method
> for converting an integer into a four byte array?
>
For what it's worth, here is what I ended up using, based on several
suggestions and tips. Duly noted that code which relies on byte
ordering, word size, and so forth is a Very Bad Idea and is almost
certainly unnecessary.
isLittleEndian
"Answer true if the machine on which we are executing uses little
endian byte order conventions."
^ ((ReadStream on: (ByteArray newFrom: #(0 0 4 210))) nextNumber: 4) == 1234
isBigEndian
"Answer true if the machine on which we are executing uses big
endian byte order conventions."
^ self isLittleEndian not
byteArrayFromInteger: anInteger
"Convert anInteger into a four byte ByteArray in machine dependent
byte ordering. Assumes 32 bit integer word size for this machine."
| b |
b _ ByteArray new: 4.
self isBigEndian
ifTrue: [(WriteStream on: b) nextNumber: 4 put: anInteger]
ifFalse: [(WriteStream on: b) nextLitteEndianNumber: 4 put: anInteger].
^ b
integerFromByteArray: anArrayOfFourBytes
"Convert a four byte ByteArray in machine dependent byte ordering
to an integer. Assumes 32 bit integer word size for this machine."
^ anArrayOfFourBytes longAt: 1 bigEndian: self isBigEndian
More information about the Squeak-dev
mailing list
|