Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Foundation where
- -- Returns a 'zeroed' unsigned 8 bit byte.
- nullByte :: [Bool]
- nullByte = take 8 (repeat False)
- -- Addition for two unsigned 8 bit bytes.
- add :: [Bool] -> [Bool] -> [Bool]
- add x y = addWith x y False
- -- Multiplication of two unsigned 8 bit bytes.
- multiply :: [Bool] -> [Bool] -> [Bool]
- multiply xs ys = multiplyWith xs (asInteger ys)
- -- Multiplication of two unsigned 8 bit bytes with counter.
- multiplyWith :: [Bool] -> Integer -> [Bool]
- multiplyWith xs 0 = nullByte
- multiplyWith xs n = if (n == 1) then xs else add xs (multiplyWith xs (n - 1))
- -- Addition implementation for two unsigned 8 bit bytes and a carry bit.
- addWith :: [Bool] -> [Bool] -> Bool -> [Bool]
- addWith [] [] _ = []
- addWith (x:xs) (y:ys) carry
- | (x == y) = carry : addWith xs ys (x && y)
- | otherwise = (not carry) : addWith xs ys carry
- -- Converts an Integer to an unsigned 8-bit byte.
- asByte :: Integer -> [Bool]
- asByte n =
- if (n == 0) then nullByte else (byteWithBit p nullByte) `ord` (asByte (n - 2^p)) where p = log2 n
- -- Converts an unsigned 8-bit byte to an Integer.
- asInteger :: [Bool] -> Integer
- asInteger xs = asIntegerWith xs 0
- -- Converts an unsigned 8-bit byte to an Integer with a bit position.
- asIntegerWith :: [Bool] -> Integer -> Integer
- asIntegerWith [] _ = 0
- asIntegerWith (x:xs) p = (if x then 2^p else 0) + asIntegerWith xs (p + 1)
- -- Performs a bitwise OR between two unsigned 8-bit bytes.
- ord :: [Bool] -> [Bool] -> [Bool]
- ord xs ys = zipWith (||) xs ys
- -- Returns a 8-bit unsigned byte with the desired bit set (least significant -> most significant).
- byteWithBit :: Integer -> [Bool] -> [Bool]
- byteWithBit n (b:byte)
- | (n > 7 || n < 0) = nullByte
- | n == 0 = True : byte
- | otherwise = b : byteWithBit (n - 1) byte
- -- Returns the nearest Integer power of 2 to the given Integer.
- log2 :: Integer -> Integer
- log2 n = toInteger l where l = length (takeWhile (<= n) (map (2^) [1..]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement