Haskell 程序用于查找给定数字的 1 的补码
本教程将帮助我们找到给定数字的 1 的补码。二进制数字的 1 的补码是通过反转数字的每个位来找到的。1 变成 0,0 变成 1。这也称为按位非运算。数字的 1 的补码在某些类型的错误检测和错误校正示例以及某些类型的数字逻辑电路中很有用。 1 的补码最常见的用途是在有符号数表示中,它用于表示负数。
例如,如果数字的二进制表示形式为"1010",则其 1 的补码将为"0101"。
算法
步骤 1 - 导入 Data.Bits 模块以使用补码函数。
步骤 2 - 定义 onesComplement 函数。
步骤 3 - 程序执行将从主函数开始。main() 函数完全控制程序。它写为 main = do。
步骤 4 - 名为"num"的变量正在初始化。它将包含要计算其 1 的补码的数字。
步骤 5 - 使用"putStrLn"语句和 show 函数显示最终结果值。
使用补码函数
在此示例中,我们将数字传递给onesComplement 函数,然后该函数使用补码函数找到数字的 1 的补码。然后它打印原始数字的 1 的补码。
示例 1
import Data.Bits onesComplement :: Int -> Int onesComplement n = complement n main :: IO () main = do let num = 10 putStrLn $ "The 1's complement of " ++ show num ++ " is " ++ show (onesComplement num)
输出
The 1's complement of 10 is -11
使用 bitSize 函数
在此示例中,onesComplement 函数使用输入数字的 bitSize 来计算该位数可以表示的最大值。然后,它从这个最大值中减去输入数字以找到 1 的补码。
示例 2
import Data.Bits onesComplement :: Int -> Int onesComplement n = (2^(bitSize n) - 1) - n main :: IO () main = do let num = 10 putStrLn $ "The 1's complement of " ++ show num ++ " is " ++ show (onesComplement num)
输出
The 1's complement of 10 is -11
使用 xor 函数
在此示例中,我们将从 Data.Bits 模块导入特定的 xor 函数和 shiftL 运算符,以查找给定数字的 1 的补码。
示例 3
import Data.Bits (finiteBitSize, xor, shiftL) onesComplement :: Int -> Int onesComplement n = n `xor` (1 `shiftL` finiteBitSize n - 1) main :: IO () main = do let num = 10 putStrLn $ "The 1's complement of " ++ show num ++ " is " ++ show (onesComplement num)
输出
The 1's complement of 10 is -11
结论
在 Haskell 中,有多种方法可以找到给定数字的 1 的补码。这可以通过使用补码函数、使用 bitSize 函数或使用 xor 函数来实现。二进制数的 1 的补码是通过反转数字的每个位来找到的。1 变成 0,0 变成 1。这也称为按位非运算。1 的补码最常见的用途是在有符号数表示中,它用于表示负数。