This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

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: -- (:) From: David MENTRE Subject: Re: [Caml-list] How to handle endianness and binary string conversion for 32 bits integers (Int32)?
```Hello,

"Nicolas Cannasse" <warplayer@free.fr> writes:

> Extlib IO module have some code about that,
> See http://ocaml-lib.sourceforge.net/doc/IO.html

I've look at this code but, from a quick look, it seems to handle only
OCaml int.

For what is worth, here is my own weel (here under public domain

<<timestamp.ml>>=
open Int32
@

\section{32 bits integer to/from string conversion}

Function [[be_of_int32]] converts an [[Int32]] into its big
endian binary representation.

<<timestamp.ml>>=
let be_of_int32 n =
let byte_mask = of_int 0xff in
let char_of_int32 x = Char.chr (to_int x) in
let d0 = char_of_int32 (logand n byte_mask) in
let d1 = char_of_int32 (logand (shift_right_logical n 8) byte_mask) in
let d2 = char_of_int32 (logand (shift_right_logical n 16) byte_mask) in
let d3 = char_of_int32 (logand (shift_right_logical n 24) byte_mask) in
let big_endian = String.make 4 d3 in
big_endian.[1] <- d2;
big_endian.[2] <- d1;
big_endian.[3] <- d0;
big_endian
@

Function [[int32_of_be]] converts an big endian binary
representation of a 32 bits integer into an [[Int32]].

<<timestamp.ml>>=
let int32_of_be be =
if String.length be <> 4 then
raise (Invalid_argument "int32_from_big_endian");
let d3 = of_int (Char.code be.[3])
and d2 = of_int (Char.code be.[2])
and d1 = of_int (Char.code be.[1])
and d0 = of_int (Char.code be.[0]) in
(logor (shift_left d0 24)
(logor (shift_left d1 16)
(logor (shift_left d2 8) d3)))
@

\section{Automatic tests}

<<timestamp.ml>>=
let _ =
if Config.do_autotests then begin
Printf.printf "  timestamp autotests...";
assert(int32_of_be "\001\002\003\004" = of_string "0x01020304");
assert(be_of_int32 (of_string "0x01020304") = "\001\002\003\004");
assert(int32_of_be "\255\254\253\252" = of_string "0xfffefdfc");
assert(be_of_int32 (of_string "0xfffefdfc") = "\255\254\253\252");
Printf.printf "done\n"
end
@

Yours,
d.
--
pub  1024D/A3AD7A2A 2004-10-03 David MENTRE <dmentre@linux-france.org>
5996 CC46 4612 9CA4 3562  D7AC 6C67 9E96 A3AD 7A2A

```