Reputation: 669
Is there anyway to convert String
to BinaryLiterals
type?
For example "11001100"
to 0b11001100
Upvotes: 2
Views: 129
Reputation: 233125
Using readBin
from https://stackoverflow.com/a/5922212/126014, you can parse a binary string representation of a number into an Maybe Integral
of your choice, e.g.:
*Q48065932> readBin "11001100"
Just 204
11001100
is just the binary representation of the (decimal) integer 204
. Using BinaryLiterals
, you can write that number using binary representation:
*Q48065932> :set -XBinaryLiterals
*Q48065932> Just 0b11001100
Just 204
If you want the integer to be a particular type (say: Word8
), you can do that for both expressions:
*Q48065932 Data.Word> readBin "11001100" :: Maybe Word8
Just 204
*Q48065932 Data.Word> Just 0b11001100 :: Maybe Word8
Just 204
You can convince yourself that these two expressions have the same value by comparing them:
*Q48065932 Data.Word> readBin "11001100" == Just 0b11001100
True
You can also write the number 204
using hexadecimal notation, like this:
*Q48065932 Data.Word> Just 0xCC
Just 204
That's still equal to 11001100
:
*Q48065932 Data.Word> Just 0xCC == readBin "11001100"
True
*Q48065932 Data.Word> Just 0xCC == Just 204
True
All of these expressions are equal to each other because they're the same number (204
); they're just different ways to write the same number. The data type used to store that number in memory (Int
, Word8
, etc.) is independent of how you write the literal numbers.
Upvotes: 4