[Haskell-cafe] Detecting system endianness

Don Stewart dons at galois.com
Thu Dec 18 23:07:00 EST 2008


Foreign.Storable.sizeOf

wren:
> In a similar vein, is there already a function available to give the 
> size of Word in bytes? Or should I write the usual Ptr conversion tricks 
> to figure it out?
> 
> 
> 
> Holger Siegel wrote:
> >On Thursday 18 December 2008 13:40:47 Ryan Ingram wrote:
> >>Actually, this is probably safer:
> >>
> >>import Foreign.Marshal.Alloc
> >>import Foreign.Ptr
> >>import Foreign.Storable
> >>import Data.Word
> >>import System.IO.Unsafe
> >>
> >>endianCheck = unsafePerformIO $ alloca $ \p -> poke p (0x01020304 ::
> >>Word32) >> peek (castPtr p :: Ptr Word8)
> >>
> >>littleEndian = endianCheck == 4
> >>bigEndian = endianCheck == 1
> >>
> >>  -- ryan
> >
> >
> >Using modules Data.Binary, Data.Binary.Put and Data.Word, you can define
> >
> >  littleEndian =  (decode $ runPut $ putWord16host 42 :: Word8) == 42
> >
> >Under the hood, it also uses peek and poke, but it looks a bit more 
> >functional.
> 
> 
> -- 
> Live well,
> ~wren
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


More information about the Haskell-Cafe mailing list