[Haskell-cafe] Endian conversion

Joel Reymont joelr1 at gmail.com
Mon Oct 3 15:06:08 EDT 2005


On Oct 3, 2005, at 6:51 AM, Marc Ziegert wrote:

> data (Integral a) => BigEndian a = BigEndian a deriving  
> (Eq,Ord,Enum,...)
> be = $( (1::CChar)/=(unsafePerformIO $ with (1::CInt) $ peekByteOff  
> `flip` 0) ) :: Bool

Will this always correctly determine if the platform is big-endian?  
How does it actually work?

> instance (Storable a) => Storable (BigEndian a) where
>  sizeOf (BigEndian a) = sizeOf a
>  alignment (BigEndian a) = alignment a
>  peek = if be then peek0 else peekR
>   where
>    peek0 (BigEndian a) = peek a
>    peekR = peekByteOff `flip` 0
>  peekByteOff = if be then peekByteOff0 else peekByteOffR
>   where
>    peekByteOff0 (BigEndian a) = peekByteOff a
>    peekByteOffR (BigEndian a) i = peekByteOff a (sizeOf a - 1 - i)
> ...poke...

So I would need to implement the various functions from storable, right?

Also, what's the easiest way to implement LittleEndian on top of  
this? Just change peekByteOf, etc.?

     Thanks, Joel

--
http://wagerlabs.com/idealab







More information about the Haskell-Cafe mailing list