[Newbies] Reading and writing C structs

Bert Freudenberg bert at freudenbergs.de
Tue Jul 1 09:42:14 UTC 2008

Am 01.07.2008 um 07:27 schrieb David Finlayson:

> OK, I've got an object that can read int and uint for 8, 16, 24 and 32
> bit numbers from a binary file stream. But I cant figure out how to
> read a float or double. What I want is something like this (these
> don't work):
> double
> 	| n |
> 	n := Float from: (aFileStream next: 32).
> 	^n
> float
> 	| n |
> 	n := Float from: (aFileStream next: 16).
> 	^n
> Any tips?

Well, for one, C floats are 4 bytes and doubles are 8 bytes as defined  
by IEEE, so your code couldn't possibly work.

Secondly, Squeak Floats are represented as C doubles (inspect a Float,  
you will see two 32-bit words = 8 bytes), only in FloatArrays we have  
single-precision (32 bits = 4 bytes) floats that are converted to/from  
doubles on the fly when you access them.

You can see how to read/write Floats (doubles) in the readFloat:/ 
writeFloat: methods of DataStream. And to convert a Float into the bit  
pattern for singles there is Float>>asIEEE32BitWord and Float  

If speed was a concern you could use a FloatArray and set/get the 32  
bit word using #basicAt:/#basicAt:put: for about a 3x speed-up.

- Bert -

More information about the Beginners mailing list