Re: How to print an array of char backward.
- From: Tomás Ó hÉilidhe <toe@xxxxxxxxxxx>
- Date: Sat, 31 May 2008 11:11:36 -0700 (PDT)
On May 30, 8:34 pm, hank <ilona-radema...@xxxxxxxxxxx> wrote:
do {
if (dec % 2 == 0)
strcat(bin, "0");
else {
strcat(bin, "1");
dec--;
}
dec = dec / 2;
} while (dec > 0);
This algorithm can be written differently depending on whether you do
or do not want leading zeroes.
My major criticism of your original code is that it takes a human
approach rather than a computer approach. A computer approach would be
to use (x & 1) instead of (x % 2), and also to use shifting instead of
division by 2.
If I didn't want leading zeroes, I'd go with something like the
following:
(Disclaimer: Untested code thrown together in the last two minutes)
#define QUANTITY_VALUE_BITS(int_type) /* fancy macro */
void GetBinary(unsigned const val, char *p)
{
unsigned mask = 1u << (QUANTITY_VALUE_BITS(unsigned) - 1);
do if (val & mask) goto We_Have_Ones;
while (mask >> = 1);
/* If here is reached, there's no 1's */
p[0] = '0';
p[1] = 0;
return; /* <--- And we're gone! */
We_Have_Ones:
*p++ = '1';
while (mask >>= 1) *p++ = (val & mask ? '1' : '0');
*p = 0;
}
.
- Follow-Ups:
- Re: How to print an array of char backward.
- From: pete
- Re: How to print an array of char backward.
- References:
- How to print an array of char backward.
- From: hank
- How to print an array of char backward.
- Prev by Date: Re: printing error messages
- Next by Date: Re: function
- Previous by thread: Re: How to print an array of char backward.
- Next by thread: Re: How to print an array of char backward.
- Index(es):