[clean-list] Serializing Atomic Data Types...

John van Groningen johnvg@cs.kun.nl
Tue, 21 Nov 2000 16:32:47 +0000


>Is there an efficient means to convert Reals and Ints to their binary
>representation stored in a String, and back ?

For integers you can use >> and toChar, e.g.:

char0 = toChar (i>>24)
char1 = toChar (i>>16)
char2 = toChar (i>>8)
char3 = toChar i

>In C, provided some care is taken about the byte alignment of structures
>member, it is possible to use a union to implement that conversion in
>constant time, as is illustrated below.
>
>union {
>  unsigned long unsignedLong ;
>  struct {
>    char byte0 ;
>    char byte1 ;
>    char byte2 ;
>    char byte3 ;
>  } unsignedLongBytes ;
>}
>
>I am considering the implementation of binary serialization of some data
>structures, but am stuck for the atomic data types Int and Real...

For reals you could use the following (not really Clean) functions, to split
a 64 bit real representation into two 32 bit integers:

real_to_binary :: !Real -> (!Int,!Int);
real_to_binary _ = code {
        pop_b 0
        };

binary_to_real :: !(!Int,!Int) -> Real;
binary_to_real _ = code {
        pop_b 0
        };

Start = binary_to_real (real_to_binary 1.23);

This representation using integers is machine dependent, and the order of the
integers depends on whether the program is running on a little or big endian 
processor.

Regards,

John van Groningen