I know how I would solve that, but it awfully sounds like a homework assignment...?!?
How goes the saying?
"If I would solve it for you, you would pass your test without knowing how to do it, graduate without knowing how to do it, get a job without knowing how to do it, end up in my team without knowing how to do it. And then I would have to apply serious bodily harm..."
Hint: Think '% 2'.
Every good solution is obvious once you've found it.
"If I would solve it for you, you would pass your test without knowing how to do it, graduate without knowing how to do it, get a job without knowing how to do it, end up in my team without knowing how to do it. And then I would have to apply serious bodily harm..."
This is not my homework assignment or any. My friend just asked me it. I gave him one solution using '%', but, that seemed like a big solution to me. Many guys here will have different solution. That's why I posted it here.
you will have to use some kind of iteration or recursion, and you will need a conditional (explicit or implicit (such as a loop)) to decide when to stop.
unless you use a map of all possible integers to their strings, which get out of hand, as Solar said.
i wonders, what is the point of this?
--- solar: it seems your version #1 does not handle zero.
---
void print_bin(int val){
int high=val/2;
if(high) // if there are higher-order digits, print them first
print_bin(high);
putchar('0'+val%2); // and the lowest digit
};
The simplest method that should work for virtually any number uses % 2, then converts the binary number into it's ASCII equivalent.
That was the solution given by me using '%' and converting the remainder to character. But, just one question. If I define two bits in a structure like,
They will take up the size of the two integers...
If you want to have a real bitmap, that only needs a bit to store a bit, you will need 1 byte for 8 bits (wow ) and set the individual bits using bitwise operations.
Freanan wrote:
They will take up the size of the two integers...
Erm... sorry but that's wrong.
ISO/IEC 9899:1999 (C99) sais in 6.7.2.1 "Structure and union specifiers", paragraph 10:
An implementation may allocate any addressable storage unit large enough to hold a bit field. If enough space remains, a bit field that immediately follows another bit field in a structure shall be packed into adjacent bits of the same unit. If insuddicient space remains, whether a bit field that does not fit is put into the next unit or overlaps adjacent units is implementation defined. The order of allocation of bit fields within a unit (high order to low order or low order to high order) is implementation defined. The alignment of the addressable storage unit is unspecified.