Haskell Radix Conversion using ByteStrings


/ Published in: Haskell
Save to your folder(s)

Another radix conversion, when you need to zippy greatness of Haskell's ByteString.(Haskell strings are slooooow!)

TODO: rewrite this using overloaded strings.


Copy this code and paste it in your HTML
  1. import qualified Data.ByteString.Lazy.Char8 as BS
  2.  
  3. convertFromDecimal :: Int -> Int -> BS.ByteString -> BS.ByteString
  4. convertFromDecimal num toBase accum
  5. | toBase < 0 = error "base must be greater than zero"
  6. | toBase > 20 = error "base must be <= 20"
  7. | num < 0 = error "number cannot be negative"
  8. | num <= 0 = accum
  9. | num > 0 =
  10. let chars = "0123456789ABCDEFGHIJ"
  11. over = num `mod` toBase
  12. remain = num `div` toBase
  13. accum' = BS.cons (chars !! over) accum
  14. in
  15. convertFromDecimal remain toBase accum'

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.