One complement is not flipping all bits.
To flip bits, you need to use a xor
operation with an argument with the number of bits 1 you want the significance.
Also you can't negate an binary from arbitrary number. You need to define the number of bits you are flipping. This example will show you why:
> 0b000001 ^ 0b1
=> 0
> 0b000001 ^ 0b11
=> 2
> 0b000001 ^ 0b111
=> 6
> 0b000001 ^ 0b1111
=> 14
What you can do is define that an arbitrary number of bits is the minimum number of bits you need to represent your number. This is most likely not what you want, however, the following code can do this for you:
def negate_arbitrary_number(x)
# size is the number of significants digits you have on x.
size = 0
while (a >> size) != 0
size += 1
end
# this is the binary with all number 1's on
mask = ("1"*size).to_i(2)
# xor your number
x ^ mask
end
or this code:
def negate_arbitrary_number(x)
x.to_s(2).unpack("U*").map{|x| x == 49 ? 48 : 49}.pack("U*")
end
you might want to do a simple benchmark to test it.