سؤال

Is there a simple function I can copy and paste to make this conversion? The Ruby equivalent would be

bytes.unpack("n*")
هل كانت مفيدة؟

المحلول

Use the cereal or binary package, decode into a 16 bit unsigned int (Word16) then convert that value to a full Integer:

import Data.Serialize
...
someFunction = ...
    let intVal = runGet (fromIntegral `fmap` getWord16be) bytes

Edit:

As with any monad in haskell, you can use higher level function such as replciateM along with the above code to get a list of int values (untested code follows):

import Data.Serialize
...
someFunction = ...
    let intVals = runGet (do n <- get
                             replicateM n (fromIntegral `fmap` getWord16be)) bs

نصائح أخرى

EDIT:

Based on Thomas M. DuBuisson's suggestions, here's my solution:

eitherIntVal :: B.ByteString -> Either String [Integer]
eitherIntVal = runGet (do 
    xs <- replicateM 5 (Just `fmap` getWord16be <|> return Nothing)
    return $ map fromIntegral $ catMaybes xs) 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top