Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 507
SindreKjr Avatar asked Jan 12 '18 21:01

SindreKjr


People also ask

How do you convert hexadecimal to binary?

Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

Can hex convert to binary directly?

Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.

How do you convert from hexadecimal to numeric?

The conversion of hexadecimal to decimal is done by using the base number 16. The hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0 from the right moving forward towards the right with the increase in power. For the conversion to complete, the multiplied numbers are added.


2 Answers

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]
like image 51
K. A. Buhr Avatar answered Oct 11 '22 22:10

K. A. Buhr


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.

like image 24
Eric Avatar answered Oct 12 '22 00:10

Eric