summaryrefslogtreecommitdiff
path: root/Data/BaseConvert.hs
diff options
context:
space:
mode:
Diffstat (limited to 'Data/BaseConvert.hs')
-rw-r--r--Data/BaseConvert.hs30
1 files changed, 30 insertions, 0 deletions
diff --git a/Data/BaseConvert.hs b/Data/BaseConvert.hs
new file mode 100644
index 0000000..655f593
--- /dev/null
+++ b/Data/BaseConvert.hs
@@ -0,0 +1,30 @@
1module Data.BaseConvert (toString, toNum, toAlphaDigit, fromAlphaDigit) where
2
3import Data.Sequence
4import Data.Foldable (toList)
5import Data.List
6import Data.Char
7
8digit_alphabet :: [Char]
9digit_alphabet = ['0'..'9'] ++ ['A'..]
10
11toBase :: (Integral a) => a -> a -> [a]
12toBase _ 0 = [0]
13toBase b v = toList $
14 unfoldl (\n -> if n == 0 then Nothing else Just (n `divMod` b)) v
15
16toAlphaDigit :: (Integral a) => a -> Char
17toAlphaDigit = (digit_alphabet !!) . fromIntegral
18
19toString :: (Integral a) => a -> a -> String
20toString b v = map toAlphaDigit (toBase b v)
21
22fromAlphaDigit :: (Num a) => Char -> a
23fromAlphaDigit v = fromIntegral n
24 where Just n = elemIndex (toUpper v) digit_alphabet
25
26fromBase :: (Num a) => a -> [a] -> a
27fromBase b = foldl (\n k -> n * b + k) 0
28
29toNum :: (Num a) => a -> String -> a
30toNum b v = fromBase b (map fromAlphaDigit v)