Reading a number from another base
Decimal, binary, and hexadecimal are widely used numeral systems that are often represented using a string. This recipe will show how to convert a string representation of a number in an arbitrary base to its decimal integer. We use the readInt
function, which is the dual of the showIntAtBase
function described in the previous recipe.
How to do it...
Import
readInt
and the following functions for character manipulation as follows:import Data.Char (ord, digitToInt, isDigit) import Numeric (readInt)
Define a function to convert a string representing a number in a particular base to a decimal integer as follows:
str 'base' b = readInt b isValidDigit letterToNum str
Define the mapping between letters and numbers for larger digits, as shown in the following code snippet:
letterToNum :: Char -> Int letterToNum d | isDigit d = digitToInt d | otherwise = ord d - ord 'a' + 10 isValidDigit :: Char -> Int isValidDigit d = letterToNum d >= 0
Print...