Reputation: 21
I have an assignment to convert a number from decimal to binary. My problem is that I need to have it printed out directly from the function, instead of returning it back to main. Due to this, my printed out code is in the wrong order. (ex: for 6, my code prints out 011
instead of 110
)
This is what I have been using for the function:
int printBinary(int integer) {
int remainder;
if (integer < 1) {
return 0;
} else {
remainder = integer % 2;
printf("%d", remainder);
integer = integer / 2;
printBinary(integer);
return 0;
}
}
Does anyone have a suggestion on how I can print it out in reverse, or a different approach entirely?
Upvotes: 2
Views: 702
Reputation: 4288
Also you could try something like this
#include <stdio.h>
#include <limits.h>
void printBinary(int num) {
int i;
// findind the first non 0 binary position from MSB
for (i = sizeof(int) * CHAR_BIT - 1; i >= 0 && (num & (1 << i)) == 0; i--);
for (; i >= 0; i--) // start the printing from here, so trailing 0's avoided
if ((num & (1 << i)) == 0)
printf("0");
else
printf("1");
}
int main()
{
printBinary(6);
return 0;
}
Upvotes: 0
Reputation: 144695
You should just print the digit after the recursive call that prints the higher order bits.
Note also that your function prints nothing for 0
, which is probably incorrect.
Here is a simplified version:
int printBinary(int integer) {
if (integer > 1)
printBinary(integer / 2);
printf("%d", integer % 2);
return 0;
}
Upvotes: 2
Reputation: 38405
Your function prints binary digits starting from the tail. Just change the order of recursive call and printf.
int printBinary(int integer) {
int remainder;
if (integer < 1) {
return 0;
}
else {
printBinary(integer / 2);
remainder = integer % 2;
printf("%d", remainder);
return 0;
}
}
It was
printBinary(6);
printf("%d", 0);
printBinary(3);
printf("%d", 1);
printBinary(1);
printf("%d", 1);
printBinary(0);
It is now
printBinary(6);
printBinary(3);
printBinary(1);
printBinary(0);
printf("%d", 1);
printf("%d", 1);
printf("%d", 0);
Upvotes: 1