Reputation: 65
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!
Upvotes: 2
Views: 956
Reputation: 11218
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'
Upvotes: 5
Reputation: 11227
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 zip
ing 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.
Upvotes: 4