# 24-bit two's complement division in AVR assembly

How do I perform a division by 2 of the 24-bit two's complement value in registers r6:r5:r4. (r6 is the most significant byte.)

From what I have this is what I tried:
ASR r6;ASR r5;ASR r4;
but I am not sure whether I did it correctly.

My thought process is that by shifting every bit to the right lets say a 4 bit binary 1110, by shifting to the right from MSB will be 0111. and therefore 0111 is half of 1110. But I am not too sure I have done it correctly.

• shifting right doesn't work in 2's complement because the most significant bit is the sign bit. i.e. a negative number becomes positive! – Chu Apr 29 '18 at 11:18
• @Chu - The ASR instruction is correct for the first shift as it has a special feature to duplicate the upper bit on the right shift thus preserving the sign of the result. – Michael Karas Apr 29 '18 at 11:22
• @MichaelKaras yes, that works, my mistake. I'm not familiar with that language. – Chu Apr 29 '18 at 11:32
• @Chu - Then you should have learned something here. Can be good to investigate before giving comments. – Michael Karas Apr 29 '18 at 11:39
• @MichaelKaras It was a comment, not an answer, and my comment is perfectly correct in response to the OP's last general paragraph. It would be good if everyone were perfect. – Chu Apr 29 '18 at 11:44

In the mode that you tried you are just dividing the byte value in each of the three registers by two. To get this to work for multiple bytes like r6:r5:r4 you need to code this in a way that propagates the low bit from the first shift into the next byte and similar for the next byte. The proper instruction sequence to perform this would be:

ASR R6
ROR R5
ROR R4


Read the description of the ROR instruction to understand how the CY bit is used to propagate bits from register to register during the above sequence.

• won't the result be the same if i just ROR for r5 and r4, because it is just simply rotating？ Thank you for your explanation! – Jay Sun Apr 29 '18 at 10:09
• @JaySun he literally told you to read the description of the ROR instruction. It is the right instruction for this job. It inserts the carry bit to the left side, so now your register is 9 bits. Then move bit 1 to 9 into its register and move bit 0 to the carry flag. – Harry Svensson Apr 29 '18 at 10:18

When you shift right two's complement value to divide it by 2, keep the MSB equal to "1". In you example -2=1110. Dividing it by 2 will result in 1111 (note that MSB is "1" not "0" like you wrote). 1111 = -1