Base Number Conversion

Is there a platform feature that will do the following?

convertBase :: (Num a, Num b) => Int -> Int -> [a] -> [b] 

Convert a number from base 'a' to base 'b', where each list item is a number in a number. eg:

 convertBase 2 10 [1,1,0,1] = [1, 3] 

I hope this makes sense let me know if I can clean something

+6
source share
3 answers

Using the digits package from Hackage:

 import Data.Digits (digits, unDigits) convertBase :: Integral a => a -> a -> [a] -> [a] convertBase from to = digits to . unDigits from 

You can add fromIntegral there if you need different types of input and output. Also, the Integral constraint makes more sense than Num , since you probably don't want to deal with complex digits or floating point digits.

+13
source

The closest thing on the haskell platform is the Numeric module:

readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS

 fromBase :: Int -> String -> Int fromBase base = fst . head . readInt base ((<base).digitToInt) digitToInt toBase :: Int -> Int -> String toBase base num = showIntAtBase base intToDigit num "" fromBaseToBase :: Int -> Int -> String -> String fromBaseToBase from to = toBase to . fromBase from 
+7
source

A couple of ideas:

  • use showIntAtBase or Text.printf to convert to string and convert back to another base
  • write yourself - it's easier when one base is always a multiple of another

Here is a link that may help you: http://rosettacode.org/wiki/Non-decimal_radices/Convert#Haskell - Non-Discriminative Dimensions / Conversion

+2
source

Source: https://habr.com/ru/post/912492/


All Articles