I have a recursive method to convert a decimal number to a binary number in C
long decimalToBinary(long n){if(n == 0) {return 0;} else {return (10*decimalToBinary(n/2))+(n%2);}}
It is printing out the correct output, but i'm trying to have it place leading zero's and before the binary number if it is not divisible by 4 and print it out in groups of 4
. (eg. 100101100
-> 0001 0010 1100
)
I was thinking about using an array, and instead of returning the answer like I am now, putting it into an array and modifying it up in the main()
method. Then I could add a space and add zeros in the beginning.
Is there a better way to accomplish this?
Best Answer
In decimalToBinary
, instead of creating a decimal value, you can create a char
array. This char
array will contain the binary digits in reverse order, so when you print the array in your main
function, you need to print them in reverse order.
The decimalToBinary
will look like:
char *decimalToBinary(long n){int rem, mult = -1, i = 0, len = 5;char *arr = (char *) calloc(len, sizeof(char));// Loop until multiplier is not 0while (mult != 0) {mult = n / 2;rem = n % 2;n = mult;// If we are approaching end of string, increase its sizeif (mult != 0 && i == len) {len += 4;arr = (char *) realloc(arr, len);}arr[i++] = rem + '0'; // Convert int to char}arr[i] = '\0'; // End-of-string characterreturn arr;}
You can then call this function from main
and print it like this:
// Convert decimal to binary (char array)char *arr = decimalToBinary(n);// Print leading 0sint len = strlen(arr);int padding = (len % 4) == 0 ? 0 : 4 - (len % 4);int count = 0;while (padding > 0) {printf("0");--padding;++count;}// Print the binary digits in reverse int i = len - 1;while (i >= 0) {// Print a space after every 4 charsif (count > 0 && count % 4 == 0) {printf(" ");}printf("%c", arr[i]);--i;++count;}printf("\n");
I've tried this code out and it works. For example, the decimal number 280
will print out as 0001 0001 1000
.