[Haskell-cafe] Endian conversion

Donn Cave donn at drizzle.com
Thu Oct 6 14:23:09 EDT 2005

On Thu, 6 Oct 2005, Joel Reymont wrote:
> I don't want to replicate all the code in NewBinary for Little/Big  
> endian. I'm looking for an elegant solution (Haskell, the elegant  
> language, you know).

Maybe that's why I haven't seen anyone propose a foreign interface,
but it's sure how I would do it.  This standard network library stuff
is all sorted out for C programmers, it's just a matter of getting to it.
Code for htonl follows, htons should obvious.  For floats, I suppose
you'd deliver them across the interface as whatever the floating point
equivalent of CInt, then make sure they're 32 bit floats on the C
side before swapping them with htonl.

	Donn Cave, donn at drizzle.com

--- Netword.hsc ---
-# OPTIONS -fffi #-}
module Netword (htonl,ntohl) where
import Foreign
import Foreign.C

#include "netw.h"

foreign import ccall unsafe "c_htonl" htonl :: CInt -> CInt
foreign import ccall unsafe "c_ntohl" ntohl :: CInt -> CInt

--- netw.c ---

#include <sys/types.h>
#include <arpa/inet.h>

#include "netw.h"

c_ntohl(uint32_t v)
        return ntohl(v);
c_htonl(uint32_t v)
        return htonl(v);

--- compile ---

hsc2hs -c gcc -I /usr/local/lib/ghc-6.4/include Netword.hsc
ghc -c Netword.hs
ghc -o tw Main.hs Netword.o netw.o

More information about the Haskell-Cafe mailing list