问题
Suppose I have a system that has integers that work in mod n
. So with my integers adding one to n-1
is actually equal to zero.
Suppose further that you define the twos compliment of a number to be the number when added to itself is equal to zero. That is:
x + C(x) = 0 (here C(x) is the twos compliment of x)
What in general should I do to get the twos compliment of x?
The real problem:
If x is a number in binary I could just invert all of the the bits of x and then add one to that number.
This gets a little trickier if x is say a trinary number. The problem with this is that it does not match up to an even number of bits, so you would be trying to flip 2/3 of a bit or something, which I don't have any clue what would mean physically.
So my question is this: How can I take the two's compliment of a number of arbitrary base?
回答1:
I will assume that you are working on base s
for some integer s > 0
and that you are trying to express quantities modulo s^(n+1)
for some fixed integer n > 0
. In other words using at most n+1
places (or digits).
So, you represent integers in this system as sequences [xn ... x0]
where every xi
is a digit between 0
and s-1
. For example, if s=3
and n=4
, the representation [01201]
would correspond to the decimal number 0*3^4 + 1*3^3 + 2*3^2 + 0*3^1 + 1*3^0 = 27 + 18 + 1 = 46
.
Generally speaking the decimal value of the representation above would be:
x = xn*s^n + ... + x0*s^0
Now, your problem consists in finding the representation of -x
modulo s^(n+1)
(remember that we only can use s+1
"digits".
Define, for every digit xi
its complement to s
as being
c(xi) = s - 1 - xi
Note that in the binary case, when s=2
, the complemento to 2
conforms the same definition. Also notice that
xi + c(xi) = s - 1 eq(1)
Now let me use a simpler notation here and call yi = c(xi)
. Then the sequence
y = [yn ... y0]
is what we could call the complement to s
of x
. It is also the representation of -x - 1
modulo s^(n+1)
and therefore to obtain -x
you only have to add 1
to y
. For example in the case x=[01201]
we would have y=[21021]
because the digits sum 3-1=2
at each position.
The reason is simple:
[yn ... y0] + [xn ... x0]
= yn*s^n + ... + y0*s^0 + xn*s^n + ... + x0*s^n
= (yn+xn)*s^n + ... + (y0+x0)*s^0
= (s-1)*sˆn + ... + (s-1)*s^0 ; by eq(2)
= s^(n+1) + ... + sˆ1 - (s^n + ... + s^0)
= s^(n+1) - 1
= -1 modulo s^(n+1)
So, things work similarly as how they work when s=2
and, say, modulo 2^32
(32 bits). In this sense there is nothing special about the binary case.
来源:https://stackoverflow.com/questions/39681019/2s-compliment-general-form