6

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.

0

2 Answers 2

6

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]
Sign up to request clarification or add additional context in comments.

2 Comments

That's very helpful, thank you. Is there a specific reason for using Maybe and Just?
@Basillicum Not all Char values are valid hexadecimal digits. Note that hexToBin 'g' == Nothing.
3

Not sure if you could use this: How to print integer literals in binary or hex in haskell?

Haskell: recursively convert hex string to integer?

I don't think that there is a library function, but you could convert it to base 2 using a similar model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.