Well, to be honest, this is actually my homework, where I have to implement an algorithm that should be able to separate the two values ββwithout accepting their absolute values ββfor division. He must also find the rest.
A dividend is a unit with a large absolute value, and a separator has a lower absolute value.
I have done a lot of Googling, but most examples cover only unsigned values.
I tried to implement it according to the scheme mentioned in the first answer: Introduce separation with a bitwise operator. For some reason, this did not really hurt me.
Then I found the following: http://www4.wittenberg.edu/academics/mathcomp/shelburne/comp255/notes/BinaryDivision.pdf I got it when I wrote the code below, using the example at the end of the document.
This is correct if the first value is positive and the second is not.
I have been working on this for at least 2 days. Maybe someone can tell where I am going wrong.
Here is the code I managed to build using @Dysaster. It does not work when both values ββare negative or positive, but I managed to get 20 points out of 25 for this while protecting.
#include <stdio.h> #include <stdlib.h> char *bits(char Rg) { unsigned char bit = 0x80; int i; char *bits; bits = (char*) malloc(9); for (i=0; i < 8; i++) { *(bits+i) = Rg & bit ? '1' : '0'; bit >>= 1; } *(bits+i) = '\0'; return bits; } int divide(char Rg1, char Rg2) { char Rg3, r=0; int i; printf("Rg1 : %s (%2d)\n", bits(Rg1), Rg1); printf("Rg2 : %s (%2d)\n", bits(Rg2), Rg2); Rg3 = Rg1; printf("Rg3 : %s (%2d) <- copy of Rg1\n", bits(Rg3), Rg3); if (Rg1 < 0) { r = 0xff; } printf("rem : %s (%2d) <- remainder after sign check\n", bits(r), r); for (i = 0; i < 8; i++) { printf("\n ------------ %d. ITERATION ------------\n", i+1); if (Rg3 & 0x80) { printf(" - left shift r and Rg3, carry\n"); Rg3 <<= 1; r <<= 1; r += 1; printf(" > %s (%2d) | %s (%2d)\n", bits(r), r, bits(Rg3), Rg3); } else { printf(" - left shift r and Rg3\n"); Rg3 <<= 1; r <<= 1; printf(" > %s (%2d) | %s (%2d)\n", bits(r), r, bits(Rg3), Rg3); } printf(" - add in the divisor\n"); r += Rg2; printf(" > %s (%2d) | %s (%2d)\n", bits(r), r, bits(Rg3), Rg3); if (Rg1 < 0 && Rg2 > 0 && r >= 0 || Rg1 > 0 && Rg2 < 0 && r < 0) { // real ugly, I know printf(" - subtract the divisor and set the lowest bit of Rg3 to 1\n"); r -= Rg2; Rg3 |= 0x01; printf(" > %s (%2d) | %s (%2d)\n", bits(r), r, bits(Rg3), Rg3); } else { printf(" - lowest bit of Rg3 stays 0\n"); printf(" > %s (%2d) | %s (%2d)\n", bits(r), r, bits(Rg3), Rg3); } } // post division sign check if ((Rg1 < 0 && Rg2 > 0) || (Rg1 > 0 && Rg2 < 0)) { Rg3++; } printf("\n%s (%d) / %s (%d) = %s (%d) r %s (%d)\n\n", bits(Rg1), Rg1, bits(Rg2), Rg2, bits(Rg3), Rg3, bits(r), r); } int main(int argc, char *argv[]) { divide(-13, -4); // buggy divide(-29, 4); // OK divide(19, -8); // OK divide(17, 5); // buggy return 0; }