Skip to content

Instantly share code, notes, and snippets.

@Sintrastes
Last active August 29, 2015 14:19
Show Gist options
  • Save Sintrastes/bac542aec451b850657b to your computer and use it in GitHub Desktop.
Save Sintrastes/bac542aec451b850657b to your computer and use it in GitHub Desktop.
-- Long binary division algorithm, used for the CSCI 342 final project (floating point emulation).
-- Pro tip: Apparently integer division works just as well as this if you do some bit shifting.
longBinaryDivision :: Integer -> Integer -> [Bool]
longBinaryDivision num denom = go (createDivadend num) denom num 0
where go :: [Bool] -> Word32 -> Word32 -> Int -> [Bool]
go divadend divisor remainder count
| divisor == remainder = [True]
| divisor < remainder = [True] ++ go (tail divadend) divisor (carryDown (remainder - divisor)) (count +1)
| divisor > remainder = [False] ++ go (tail divadend) divisor (carryDown remainder) (count +1)
boolToInteger = fromEnum :: Integer
carryDown x = (+(boolToInteger $ head $ tail divadend)) $ shiftL x 1
createDivadend = (++ [False,False ..]) . (removeLeadingZeros . toListBE)
removeLeadingZeros (False:xs) = xs
removeLeadingZeros xs = xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment