[Haskell-cafe] Detecting system endianness

wren ng thornton wren at freegeek.org
Thu Dec 18 22:35:40 EST 2008


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


More information about the Haskell-Cafe mailing list