2

Given an 8-bit binary, I want to get its char representation. For example:

[0,1,1,0,0,0,0,1] which, I belive, is the binary representation of 'a'.

Thanks in advance!

1
  • 1
    The problem consists of two pieces. 1) Convert a list of binary digits into an Int. 2) Converting an Int to a Char. Hoogle tells us that we can use chr for that. Commented Dec 13, 2012 at 12:15

2 Answers 2

5
import Data.Char

ord2chr :: [Int] -> Char
ord2chr = chr . foldl (\a b -> 2*a + b) 0

Now you can try

> ord2chr  [0,1,1,0,0,0,0,1]
'a'
Sign up to request clarification or add additional context in comments.

Comments

4

As I suggested in my comment, the question can be split in two. Here's a suggestion for the first part, where I've for Haskellness' sake declared a Bit type:

data Bit = Zero | One

fromBits :: (Integral a) => [Bit] -> a
fromBits bits = foldl f 0 (zip [0..] (reverse bits))
    where
      f x (_, Zero) = x
      f x (n, One) = x + 2^n

So what does this do? Well, your question suggests that your bit list has the most significant bit first. We'll process it in reverse, so we do reverse bits. Then, we need to keep track of the powers of two the various elements in reverse bits represent, which is what ziping with [0..] does, producing [(0, least-significant-bit), (1, second-least-significant bit), ...]. Finally foldl consumes this list of pairs, with the helper function f adding the appropriate powers of 2 to the accumulator.

I've used the Integral typeclass to not have to choose an integral type. You can use Int, or even Word8, in your 8-bit case. For longer bit lists, one could use Integer for arbitrary precision (see also (*) below).

For the second part, we can use chr to convert an Int to Char, and if we know that our bit lists aren't too big(*), fromIntegral can convert our Integral type a to an Int.

So, what you want can be written as:

convert :: [Bit] -> Char
convert = chr . fromIntegral . fromBits

In your case, convert [Zero, One, One, Zero, Zero, Zero, Zero, One] is 'a'.

(*) Of course, if they were, the conversion wouldn't make obvious sense anyway. But here's a point I'd like to bring home: We've split the problem in two pieces, and it turns out that the first part (processing the bit list) can be solved in a way that could be useful in a more general setting. For example, fromBits (One:(replicate 100 Zero)) is 2^100.

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.