gpt4 book ai didi

ruby - 负 FixNum 的无符号等价物

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:36 26 4
gpt4 key购买 nike

如何确定负 FixNum 的无符号解释?

# unexpected, true
(~0b01111011).to_s(2) == ("-" + (~0b01111011).abs.to_s(2))

# expected, false
~0b01111011 == 0b10000100

我将如何编写这样的函数:

123.unsigned_not(8) == 132

或者:

-124.unsigned(8) == 132

编辑:我可以通过字符串做到这一点,但解决方案远不能令人满意

class Fixnum
def unsigned_not(bits=16)
to_s(2).rjust(bits,'0').gsub(/[01]/, '0' => '1', '1' => '0').to_i(2)
end
end

最佳答案

Fixnum#~ 运算符执行 Two's complement并且 Ruby 在内部使用任意大数和算术,所以如果你想在固定基数上进行反演,你需要在所需的范围内工作并相应地解释结果:

class Fixnum
def neg(base=8)
# xor with max in specific base
self ^ (2**base - 1)
end
end

132.neg # 123
123.neg # 132
~-124.neg # 132
132.to_s(2) # 1000010
132.neg.to_s(2) # 0111101
# different result for a different base, as expected
132.neg(16).to_s(2) # 111111110111101

关于ruby - 负 FixNum 的无符号等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34145891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com