转换二进制负二进制 [英] Converting binary to negative binary
问题描述
我需要一个积极的二进制转换为二进制负。
我的方法看起来有点不对。将一个元素增加到列表的末尾不会太工作。请帮帮我!
I need to convert a positive binary to a negative binary. My approach seems somehow wrong. Adding an element to the end of a list does not work too. Please help me!
twoComplement :: [Int] -> [Int]
twoComplement (x:xs) | (x:xs) == [] = [x]
| last (x:xs) == 0 = (twoComplement (init (x:xs))) ++ [1]
| last (x:xs) == 1 = (twoComplement (init (x:xs))) ++ [0]
因为你看到我是新来的Haskell。
as u see I'm new to haskell.
推荐答案
在看<一个href=\"https://en.wikipedia.org/wiki/Two%27s_complement#Converting_to_two.27s_complement_re$p$psentation\"相对=nofollow>百科,还有如何执行二进制补码转换从LSB到MSB的解释:
Looking on Wikipedia, there's an explanation of how to perform the two's complement conversion "From LSB to MSB":
一个二进制数来手动转换成两个补快捷方式是在最少显著位(LSB)开始,并将所有零(从LSB向最显著位工作),直到第1次到达;然后复制1,和翻转所有剩余位。
Working from LSB towards MSB:
A shortcut to manually convert a binary number into its two's complement is to start at the least significant bit (LSB), and copy all the zeros (working from LSB toward the most significant bit) until the first 1 is reached; then copy that 1, and flip all the remaining bits.
这个算法转换相当整齐哈斯克尔:
This algorithm translates quite neatly to Haskell:
twosComplement :: [Int] -> [Int]
twosComplement bs = zs ++ fixup rest
where
(zs, rest) = span (== 0) bs
fixup [] = []
fixup (x:xs) = x : map (1-) xs
这是落实使用@chi在他的回答提出的小尾数格式:一般情况下这是你想要处理的二进制数时使用的一个。如果你的真的的要保持它在big-endian格式,那么你将收到并应用后扭转号 twosComplement
如上定义
This implementation is using the little-endian format that @chi suggested in his answer: In general that is the one you want to use when processing binary numbers. If you really really want to keep it in big-endian format, then you will have to reverse the number before and after applying twosComplement
as defined above.
-
跨度
是用来获取所有的连续至少显著零(ZS
),以及在其他
的数量。 -
修正
将第一个1
遇到的(它会在休息的头
如果存在的话),相数的其余部分之前。
span
is used to get all the consecutive least significant zeros (zs
) as well as therest
of the number.fixup
copies the first1
encountered (it will be at the head ofrest
if it exists at all), before inverting the rest of the number.
这篇关于转换二进制负二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!