[code]#include <stdio.h>
#include <inttypes.h>
void makeBinary(int64_t n)
{
if (n) {
if (n & 1) {
makeBinary(n >> 1);
printf(“1”);
} else {
makeBinary(n >> 1);
printf(“0”);
}
}
}
void printBinary(int64_t n)
{
makeBinary(n);
printf("\n");
}
int main(int argc, const char * argv[])
{
uint64_t a = 1;
for (int i = 0; i < 64; i++) {
if (i%2) {
a <<= 1;
a |= 1;
} else {
a <<= 1;
}
}
printf("%" PRIu64 "\n", a);
printBinary(a);
return 0;
}[/code]
ibex10
2
printBinary is discriminating against zero. Zero is a perfectly good number.
Yes, you’re right! I didn’t consider zero. Here is new printBinary():
[code]void makeBinary(int64_t n, int counter)
{
counter -= 1;
if (counter) {
if (n & 1) {
makeBinary(n >> 1, counter);
printf(“1”);
} else {
makeBinary(n >> 1, counter);
printf(“0”);
}
}
}
void printBinary(int64_t n)
{
makeBinary(n, 64+1);
printf(“\n”);
}[/code]
ibex10
4
No, that is pretty messy.
This will do the job nicely:
void printBinary (int64_t n)
{
if (!n) {
printf ("0");
}
else {
makeBinary (n);
}
printf ("\n");
}
Also I would rename makeBinary to make its purpose clear.
For example:
void printBinary (int64_t n)
{
if (!n) {
printf ("0");
}
else {
void printBinaryBits (int64_t);
printBinaryBits (n);
}
printf ("\n");
}
void printBinaryBits (int64_t n)
{
if (n) {
if (n & 1) {
printBinaryBits (n >> 1);
printf ("1");
} else {
printBinaryBits (n >> 1);
printf ("0");
}
}
}
[Accelerate your learning and become a competent programmer: pretty-function.org]
Hi @abex10, I just did a quick and dirty fix. You really inspired me!