/* * Nick Pafundi * Questions or comments on this code should be * submitted at http://www.static-zero.com. * * This is a sample program that uses a decToBin * function to convert a decimal number to 2's * complement binary. */ #include #include #include /* Function Prototype */ int *decToBin(int decimal, int numBits, int binary[]); int main(int argc, char *argv[]) { /* Initialize all values */ int numBits = 10; int *binary; int num1 = 49; int num2 = -93; int i; /* Dynamically allocate array */ binary = malloc(sizeof(int)*numBits); /* Try with 49 (should be 0000110001) */ binary = decToBin(num1, numBits, binary); printf("Decimal %d in 2's complement binary is ", num1); for (i=0; i=0; i--) binary[i] = 0; /* If the number is negative, set the * flag and invert the number */ if (decimal < 0) { flag = 1; decimal = -decimal; } /* decimal%2 will give the current binary bit. * Divide by 2 to get the next bit. Do this while * decimal is larger than 0. (Note - integer division * will throw away the remainder, which must happen. */ while (decimal > 0) { binary[numBits--] = decimal%2; decimal/=2; } /* Deal with the negative number. First, take the * complement of the current bit. This number will * be 2 less than the bit we want, so add 2. Then * add the carry. If the result is > 1, it's no * longer binary, so set it to 0 and try the next * bit. Continue this until we can successfully add * the carry bit. Once it is added, or once we've * finished the loop, we're done. */ if (flag) { for(i=tmp; i>=0; i--){ binary[i] = ~(binary[i])+2; binary[i]+=carry; carry = 0; if (binary[i] > 1) { binary[i] = 0; carry = 1; } } } /* Return the array */ return binary; }