[A83] Re: Signed division by a power of two.


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

[A83] Re: Signed division by a power of two.



To test this, we first need an understanding of the binary method of
negating numbers.  The method generally used is "two's complement" by which
negating a number consists of inverting all bits and adding 1.  xor $FF\inc
a = neg a afaik.

http://www.duke.edu/~twf/cps104/twoscomp.html

so let's say we divide 4 (%00000100) by 2 using your algorithm.

 bit 7,a  ;z flag set
 jr z,pos ;a is positive
;...
pos:
 sra      ;a = %00000010 = 2 success!
endpos:

now divide -4 by 2 using your algorithm.
-4=-(4)=-(%00000100)=%11111011+1=%11111100

 bit 7,a  ;z flag reset
 jr z,pos ;a is negative
 scf      ;carry flag set
 rr a     ;a = %11111110
 jr endpos
 ;...
endpos:

a ends up being %11111110=-(%00000001+1)=-2 ; success!

Your algorithm works when dividing both negative and positive numbers.  Just
remember:
 - zero is considered positive using this code
 - the largest positive, 8-bit number is 127
 - the smallest negative, 8-bit number is -128
 - relative jumps (jr) are smaller and faster than absolute jumps (jp).
Always use relative jumps unless jumping farther than 127 bytes from the
byte AFTER the jump.

Jeff

>>>>>>>>>>>>>>>>>>>>
When dividing a signed number by two, is there any better way than this?

bit 7,a
jp z,Positive
scf
rr a
jp EndPositive
Positive:
sra
EndPositive:

Or does that way even work?  I have been having a hard time catching onto
this idea of signed numbers.

Thanks,
MWM



Follow-Ups: References: