Search code examples
haskellhexlibraries

Haskell: Library function to convert hexadecimal to binary notation


Is there a library function to convert a hexadecimal digit (0-F) to its equivalent four-digit binary value? For example, 9 = 1001, C = 1100.

I've looked at Data.Hex, Data.HexString, Numeric, and several other libraries that should be relevant, and I had assumed I would be able to find the function I am looking for. However, I'm quite new to Haskell and may be overlooking something simple.

EDIT: Not a duplicate, IMO. My question is about conversion directly from hexadecimal to binary, which the linked question (and its answers) does not mention.


Solution

  • There isn't a single library function to convert a hex digit to a binary string. You can use readHex from module Numeric to convert a hex digit to an integer and printf from the Text.Printf module to generate a binary string, like so:

    import Numeric (readHex)
    import Text.Printf (printf)
    
    hexToBin :: Char -> Maybe String
    hexToBin c
      = case readHex [c] of
          (x,_):_ -> Just $ printf "%04b" (x::Int)
          _       -> Nothing
    

    giving:

    > map hexToBin (['0'..'9'] ++ ['A'..'G'])
    [Just "0000",Just "0001",Just "0010",Just "0011",Just "0100",
    Just "0101",Just "0110",Just "0111",Just "1000",Just "1001",
    Just "1010",Just "1011",Just "1100",Just "1101",Just "1110",
    Just "1111",Nothing]