Data.Bits 对二进制表示的操作
Data.Bits operation on binary represention
我想对二进制数据使用 Data.Bits 按位运算符。
我需要使用什么数据类型?
例如,我写了这个函数:
ch :: Int8 -> Int8 -> Int8 -> Int8
ch x y z = (x .&. y) `xor` ((complement x) .|. z)
我想作为输入二进制类型或至少 String
(不是 Int
)但仍使用 Data.Bits
所以我需要更改什么才能像这样使用它? :
ch 11111111 101110011 10110101
正如所写,ch
只会取 Int8
个值,但您可以在不更改其实现的情况下放宽函数的类型:
import Data.Bits
ch :: Bits a => a -> a -> a -> a
ch x y z = (x .&. y) `xor` (complement x .|. z)
二进制值只是整数的特定表示,但为了使内容更具可读性,您可以启用 BinaryLiterals
,例如在 GHCi 中像这样:
*Q48065001> :set -XBinaryLiterals
*Q48065001> ch 0b11111111 0b101110011 0b10110101
-58
在代码文件中,您可以使用语言编译指示启用它:
{-# LANGUAGE BinaryLiterals #-}
如果您有二进制数字的字符串表示,则首先需要解析它们。参见例如Convert a string representing a binary number to a base 10 string haskell
二进制数据 I/O 的一个不错的选择是 Data.ByteString.Lazy
, a highly-optimized library for reading Word8
values. It includes analogues for most of the list and I/O functions in the Prelude
and in Data.List
, and is well-suited for efficient interactive I/O because it reads bytes in and can write them out as a lazily-evaluated list of strict arrays. It also has efficient functions to convert to and from various encodings. See also this tutorial。
我想对二进制数据使用 Data.Bits 按位运算符。 我需要使用什么数据类型? 例如,我写了这个函数:
ch :: Int8 -> Int8 -> Int8 -> Int8
ch x y z = (x .&. y) `xor` ((complement x) .|. z)
我想作为输入二进制类型或至少 String
(不是 Int
)但仍使用 Data.Bits
所以我需要更改什么才能像这样使用它? :
ch 11111111 101110011 10110101
正如所写,ch
只会取 Int8
个值,但您可以在不更改其实现的情况下放宽函数的类型:
import Data.Bits
ch :: Bits a => a -> a -> a -> a
ch x y z = (x .&. y) `xor` (complement x .|. z)
二进制值只是整数的特定表示,但为了使内容更具可读性,您可以启用 BinaryLiterals
,例如在 GHCi 中像这样:
*Q48065001> :set -XBinaryLiterals
*Q48065001> ch 0b11111111 0b101110011 0b10110101
-58
在代码文件中,您可以使用语言编译指示启用它:
{-# LANGUAGE BinaryLiterals #-}
如果您有二进制数字的字符串表示,则首先需要解析它们。参见例如Convert a string representing a binary number to a base 10 string haskell
二进制数据 I/O 的一个不错的选择是 Data.ByteString.Lazy
, a highly-optimized library for reading Word8
values. It includes analogues for most of the list and I/O functions in the Prelude
and in Data.List
, and is well-suited for efficient interactive I/O because it reads bytes in and can write them out as a lazily-evaluated list of strict arrays. It also has efficient functions to convert to and from various encodings. See also this tutorial。