[Haskell-cafe] Endian conversion

Udo Stenzel u.stenzel at web.de
Wed Oct 5 05:42:25 EDT 2005


> >Why don't you pull out 4 bytes and assemble them manually?

To that I'd like to add a snippet from NewBinary itself:

| instance Binary Word32 where
|   put_ h w = do
|     putByte h (fromIntegral (w `shiftR` 24))
|     putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
|     putByte h (fromIntegral ((w `shiftR` 8)  .&. 0xff))
|     putByte h (fromIntegral (w .&. 0xff))
|   get h = do
|     w1 <- getWord8 h
|     w2 <- getWord8 h
|     w3 <- getWord8 h
|     w4 <- getWord8 h
|     return $! ((fromIntegral w1 `shiftL` 24) .|.
|            (fromIntegral w2 `shiftL` 16) .|.
|            (fromIntegral w3 `shiftL`  8) .|.
|            (fromIntegral w4))

This obviously writes a Word32 in big endian format, also known as
"network byte order", and doesn't care how the host platform stores
integers.  No need for `hton' and `ntoh'.  To convert it to write little
endian, just copy it and reorder some lines.  (But I think, writing LE
integers with no good reason and without an enclosing protocol that
explicitly declares them (like IIOP) is a bad idea.)

[Which reminds me, has anyone ever tried implementing a Corba ORB in
Haskell?  There's a binding to MICO, but that just adds to the uglyness
of MICO and does Haskell a bit of injustice...]


> Well, I liked that bit of Template Haskell code that Marc sent. I'm  
> now stuck trying to adapt it to read Storables :-).

I don't.  It's complex machinery, it's ugly, it solves a problem that
doesn't even exist and it solves it incompletely.  It will determine the
byte order of the host system, not of the target, which fails when
cross-compiling, and it doesn't work on machines with little endian
words and big endian long words (yes, this has been seen in the wild,
though might be extinct these days).  Use it only if You Know What You
Are Doing, have a performance problem and also know that writing
integers en bloc would help with it.


> I could read a FastString from a socket since it has IO methods but I  
> don't know how to convert the FS into a pointer suitable for  
> Storable. So much to learn :-).

useAsCString might be your friend.  But so might be (fold (:) []).


Udo.
-- 
"The greatest dangers to liberty lurk in insidious encroachment by men
of zeal, well-meaning but without understanding."
	-- Brandeis
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20051005/330ae864/attachment.bin


More information about the Haskell-Cafe mailing list