writing uint16's to a binary file
Richard A. O'Keefe
ok at cs.otago.ac.nz
Mon Mar 11 23:08:43 UTC 2002
"Ken G. Brown" <kbrown at tnc.ab.ca> wrote:
Writing the numbers either endian is fine, with a slight preference for
little endian. My intent for the uint16 was to get each element of the
collection via ReadStream on it, as 16 bits for each number. I would ensure
the size is less than 65535 when I fill the collection. I'm certainly open
to finding the best way to accomplish this.
I note that my copy of Squeak 3.0 doesn't seem to have a uint16 method,
but I would expect that it would do something like
|hi lo|
self atEnd ifTrue: [^nil].
hi := self next.
self atEnd ifTrue: [^nil].
lo := self next.
^hi asciiValue * 256 + lo asciiValue
If you have a collection (c) of numbers which you know are in the range
[0,65535], and a WriteStream (s) writing to some file, and you want to
write the numbers as big-endian unsigned 16-bit integers, then you do
c do: [:n|
s nextPut: (Character value: n // 256).
s nextPut: (Character value: n \\ 256)].
If you want little-endian, just swap the two calls to #nextPut:.
Furthermore, you can put some kinds of streams into binary mode.
For example,
s := StandardFileStream newFileNamed: 'lots of numbers'.
s binary.
c do: [:n|
s nextPut: n // 256.
s nextPut: n \\ 256].
s close.
More information about the Squeak-dev
mailing list
|