-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.hs
37 lines (28 loc) · 931 Bytes
/
Common.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
module Common where
import Data.BitVector hiding (showHex)
import Types
import Numeric (showHex)
safeBitVec :: (Integral a, Show a) => Int -> a -> BV
safeBitVec n k =
if k > maxNat n then
error $ "Number "
++ show k
++ " is too large to fit in "
++ show n
++ " bits."
else
bitVec n k
bits2bytes :: [Bool] -> [Byte]
bits2bytes bits | length bits `mod` 8 == 0 = map fromInteger (pack bits)
| otherwise = error "Bit vector must have a multiple of 8 bits."
where
pack [] = []
pack bs = nat (fromBits . take 8 $ bs) : pack (drop 8 bs)
swapBytes :: [Byte] -> [Byte]
swapBytes [] = []
swapBytes (b1:b2:bs) = b2:b1:swapBytes bs
swapBytes _ = error "Must be an even number of bytes to swap."
showHex' :: (Integral a, Show a) => a -> String
showHex' x = if length s == 1 then '0':s else s
where
s = showHex x ""