Re: How to print an array of char backward.
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Sat, 31 May 2008 15:46:14 -0500
Tomás Ó hÉilidhe wrote:
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.
I disagree.
The code as written, is easy to understand.
If he were doing decimal representation,
he would be dividing by 10 instead.
It's entirely possible and likely that a compiler
will know as much as you do about these simple micro-optimizations
and generate the same machine code for (x & 1) as it does for (x % 2).
If the code is shown to be not fast enough,
then I would investigate the changes that you suggest,
otherwise legibility is a higher priority.
--
pete
.
- Follow-Ups:
- Re: How to print an array of char backward.
- From: Richard
- Re: How to print an array of char backward.
- References:
- How to print an array of char backward.
- From: hank
- Re: How to print an array of char backward.
- From: Tomás Ó hÉilidhe
- How to print an array of char backward.
- Prev by Date: Re: malloc()/realloc() - have I got this right?
- Next by Date: Re: How to print an array of char backward.
- 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):