Search code examples
haskellhexoctal

Does anyone know how to write a function in Haskell to calculate octal into hexadecimal-notation?


I was supposed to write a code in Haskell which calculates the hexadecimal-notation when I have the octal. Unfortunately, I have no Idea how to start and which functions I have to link. Could anyone help me with that?


Solution

  • First read in the octal value (drop the 'o' or other indicator) via readOct. Then, take that Integer and convert it to a hex string using showHex, and decorate as you like.

    main = do
        octStr <- getLine
        let
            val :: Integer
            (val,_):_ = readOct octStr
            hexStr = showHex val ""
        putStrLn hexStr
    

    Also, depending on how frequently you do this, you might try and avoid the String type and use either ByteString (with these show like functions) or Text (with these show like functions). Seems octal doesn't get much attention, at least not as much as decimal and hexadecimal.