English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
How to handle endianness and binary string conversion for 32 bits integers (Int32)?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-06-17 (07:29)
From: Luca Pascali <pasckosky2000@y...>
Subject: Re: [Caml-list] How to handle endianness and binary string conversion for 32 bits integers (Int32)?
David MENTRE wrote:

>Hello Nicolas,
>Nicolas George <nicolas.george@ens.fr> writes:
>>> 1. convert between big and little endian 32 bits integers;
>>Don't do that.
>Except that I'm writing a network interface that should be specified so
>that externally written programs can read my data.
>In fact, your post reminded me of a chapter of "The Practice of
>Programming" by Kernighan and Pike. They advise to read/write integers
>byte by byte using 8 bit masking and shifting.
>So I'll follow that approach, which is close to yours and is independent
>of machine endianness.
>Thank you for the tip, ;-)
C language provides, for this purpose, some functions:
(and I don't remember if there are for other formats)

hton_ functions covert numbers from machine endianess (whatever it is) 
to network endianess, ntoh_ is the contrary.

These functions are always present, if needed they swap bytes into the 
integer, otherwise they are just identity.

I can suggest to use them instead of doing the same job in Ocaml.

An alternative for doing the job in Ocaml is to convert the number in 
exadecimal through a sprintf "%08x" and covert to a char each couple 
(rember to use the *0* in the format to have a 8 chars string as 
result). Then, you can send the first couple (MSB) first to produce an 
endianess, or send the last couple (LSB) to have the other one.
On the other side, you can get characters and build the number using 
mathematical formula.

In this way you are not aware of your local endianess, but you are sure 
about the endianess of the link.
It is longer, but works.


Luca Pascali

Baretta DE&IT
A division of Baretta SRL

tel. 02 370 111 55
fax. 02 370 111 54

Our technology:


Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB