[Haskell-beginners] binary parsing problem

Alexander Polakov plhk at sdf.org
Sun Mar 24 02:07:32 CET 2013

I'm trying to parse a binary format. 
One of the components is defined like this:

 1st 2 bits : what it is
  	 00 : A double follows 
  	 01 : 1.0 
  	 10 : 0.0 
  	 11 : not used 

 Doubles are eight byte IEEE standard floating point values."

So I wrote this code which looks almost like verbatim translation
of the spec.

import Data.Binary
import Data.Binary.Get
import Control.Applicative
import qualified Data.Binary.Bits.Get as Bits

newtype DWG_BD = DWG_BD Double deriving (Show)

instance Binary DWG_BD where
    put = undefined
    get = do
    	d <- Bits.runBitGet $ Bits.getWord8 2 >>= \i ->
	     case i of
                    0 -> decode <$> Bits.getLazyByteString 8
                    1 -> return 1.0
                    2 -> return 0.0
                    _ -> fail "bad DWG_BD"
        return (DWG_BD d)

But then when I try to parse anything starting with 00 bits, I get this:

*Main> decodeFile "/tmp/foo" :: IO DWG_BD
DWG_BD *** Exception: Data.Binary.Get.runGet at position 2: demandInput:
not enough bytes

I'm 100% sure there're enough bytes in the file. I recall seeing this
problem when my record's fields were not strict, but this is not the
case here. I suppose the problem lies in getLazyByteString, but have 
no idea how to solve it.

Alexander Polakov | plhk.ru

More information about the Beginners mailing list