Advertisement
Guest User

Arithmetic Unit

a guest
Aug 22nd, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Foundation where
  2.  
  3.     -- Returns a 'zeroed' unsigned 8 bit byte.
  4.     nullByte :: [Bool]
  5.     nullByte = take 8 (repeat False)
  6.  
  7.     -- Addition for two unsigned 8 bit bytes.
  8.     add :: [Bool] -> [Bool] -> [Bool]
  9.     add x y = addWith x y False
  10.  
  11.     -- Multiplication of two unsigned 8 bit bytes.
  12.     multiply :: [Bool] -> [Bool] -> [Bool]
  13.     multiply xs ys = multiplyWith xs (asInteger ys)
  14.  
  15.     -- Multiplication of two unsigned 8 bit bytes with counter.
  16.     multiplyWith :: [Bool] -> Integer -> [Bool]
  17.     multiplyWith xs 0 = nullByte
  18.     multiplyWith xs n = if (n == 1) then xs else add xs (multiplyWith xs (n - 1))
  19.  
  20.     -- Addition implementation for two unsigned 8 bit bytes and a carry bit.
  21.     addWith :: [Bool] -> [Bool] -> Bool -> [Bool]
  22.     addWith [] [] _ = []
  23.     addWith (x:xs) (y:ys) carry
  24.         | (x == y) = carry : addWith xs ys (x && y)
  25.         | otherwise = (not carry) : addWith xs ys carry
  26.    
  27.     -- Converts an Integer to an unsigned 8-bit byte.
  28.     asByte :: Integer -> [Bool]
  29.     asByte n =
  30.         if (n == 0) then nullByte else (byteWithBit p nullByte) `ord` (asByte (n - 2^p)) where p = log2 n
  31.  
  32.     -- Converts an unsigned 8-bit byte to an Integer.
  33.     asInteger :: [Bool] -> Integer
  34.     asInteger xs = asIntegerWith xs 0
  35.  
  36.     -- Converts an unsigned 8-bit byte to an Integer with a bit position.
  37.     asIntegerWith :: [Bool] -> Integer -> Integer
  38.     asIntegerWith [] _ = 0
  39.     asIntegerWith (x:xs) p = (if x then 2^p else 0) + asIntegerWith xs (p + 1)
  40.    
  41.     -- Performs a bitwise OR between two unsigned 8-bit bytes.
  42.     ord :: [Bool] -> [Bool] -> [Bool]
  43.     ord xs ys = zipWith (||) xs ys
  44.  
  45.     -- Returns a 8-bit unsigned byte with the desired bit set (least significant -> most significant).
  46.     byteWithBit :: Integer -> [Bool] -> [Bool]
  47.     byteWithBit n (b:byte)
  48.         | (n > 7 || n < 0) = nullByte
  49.         | n == 0 = True : byte
  50.         | otherwise = b : byteWithBit (n - 1) byte
  51.  
  52.     -- Returns the nearest Integer power of 2 to the given Integer.
  53.     log2 :: Integer -> Integer
  54.     log2 n = toInteger l where l = length (takeWhile (<= n) (map (2^) [1..]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement