官术网_书友最值得收藏!

Displaying a number in another base

Strings are a natural way to represent numbers in different bases due to the inclusion of letters as digits. This recipe will tell us how to convert a number to a string that can be printed as output.

How to do it...

  1. We will need to import the following two functions:
    import Data.Char (intToDigit, chr, ord) 
    import Numeric (showIntAtBase)
  2. Define a function to represent a number in a particular base as follows:
    n 'inBase' b = showIntAtBase b numToLetter n ""
  3. Define the mapping between numbers and letters for digits larger than nine as follows:
    numToLetter :: Int -> Char
    numToLetter n
      | n < 10 = intToDigit n
      | otherwise = chr (ord 'a' n – 10)
  4. Print out the result using the following code snippet:
    main :: IO ()
    main = do
      putStrLn $ 8 'inBase' 12
      putStrLn $ 10 'inBase' 12
      putStrLn $ 12 'inBase' 12
      putStrLn $ 47 'inBase' 12
  5. The following is the printed output when running the code:
    $ runhaskell Main.hs
    
    8
    a
    10
    3b
    

How it works...

The showIntAtBase function takes in a base, the desired number, and its mapping from number to printable digit. We order our digits in the following manner: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, and so on, up to 36 characters. Putting it all together, we get a convenient way to represent a decimal number in any base.

See also

To read a string representing a number from another base as a decimal integer, refer to the Reading a number from another base recipe.

主站蜘蛛池模板: 潼南县| 同心县| 青阳县| 谢通门县| 天门市| 辽宁省| 皮山县| 黎川县| 浦北县| 久治县| 肥东县| 渑池县| 垫江县| 乌兰浩特市| 三台县| 灌南县| 桦南县| 蓬安县| 韩城市| 陵川县| 赣榆县| 古丈县| 嘉兴市| 桐乡市| 新疆| 通渭县| 龙岩市| 内黄县| 长岭县| 江城| 穆棱市| 迁安市| 蒙自县| 永新县| 科技| 巫山县| 保德县| 石景山区| 瑞丽市| 平乐县| 呼伦贝尔市|