Converting number base

岁酱吖の 提交于 2019-12-03 07:30:35

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 a fromIntegral in there if you need the input and output types to be different. Also, the Integral constraint makes more sense than Num, since you probably don't want to deal with complex or floating-point digits.

Riccardo T.

The closest thing in the haskell platform is from module Numeric:

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

Couple of ideas:

  • use showIntAtBase or Text.printf to convert to a string, and convert back to a different base
  • write it yourself -- easier when one base is always a multiple of the other

Here is a link that might help you: http://rosettacode.org/wiki/Non-decimal_radices/Convert#Haskell -- Non-decimal radices/Convert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!