Re: A82: Invert Number


[Prev][Next][Index][Thread]

Re: A82: Invert Number



On Wed, 27 Aug 1997, Matt Maurano wrote:

> I need to get the opposite of a number. In TIbasic, you could do -X->X.
> How can I do this in Asm? If I could just xor the sign bit, that should
> do it. Now, if only I understood xor and where (if there is one) the
> sign bit would be. In case it matters, I'd be using it on an 8bit
> register, probably the a reg.

Usually integers are stored in a twos complement form. In this case, if the
sign bit is set, the rest of the bits in the word are complemented. The sign
bit is where the most significant bit would be in an unsigned integer.

Just XORing the sign bit is not enough in this case.

As an example, here is a list of all the possible bit patterns and their value
for 4-bit integers.

0111= 7  0110= 6  0101= 5  0100= 4
0011= 3  0010= 2  0001= 1  0000= 0
1111=-1  1110=-2  1101=-3  1100=-4
1011=-5  1010=-6  1001=-7  1000=-8

I don't know if the Z80 has an instruction to negate integers, but you can do
it by complementing all the bits in the value, and then adding 1. 

Starting value ... 0100 = 4
Flip all bits  ... 1011 = -5
Add 1          ... 1100 = -4

As you can see, this won't work for 0 and -8. They are special cases anyway
though. -0 is still 0, and -8 has no positive counterpart, because the range
of negative numbers is always one larger than the range of positive numebrs.

With your 8-bit registers, these would be 0 and -128 of course.


References: