Article View: comp.lang.c.moderated
Article #2052Re: NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?
From: COUGER GORDON
Date: Sat, 17 Feb 1996 18:04
Date: Sat, 17 Feb 1996 18:04
89 lines
2862 bytes
2862 bytes
In article <4g176b$mrk@solutions.solon.com>,
Charles Frayer <frayer@expert.cc.purdue.edu> wrote:
>I'm converting numbers from an input file from decimal to hex, oct, and bin.
< following code completes the conversion successfully (sort of) and prints
>it to a file, but the converted numbers are printed backwards and hex numbers
>are all numbers instead of their equivalent letter values. Any ideas?
>
> while(lNumToConv > 0)
> {
> iCoeff = (lNumToConv % iBase);
> fprintf(fptrWrite, "%i", iCoeff);
> lNumToConv = (lNumToConv / iBase);
> }
> fprintf(fptrWrite, "\n");
>
>I know (literally) why they're printing backwards, but not how to correct it.
>
Here is some code that rolls the numbers off backwards are your are doing and
puts them in a string and reverses the string.
Excuse the Pascalness of the code at the time I was converting a large group
of programs from pascal. And working with retreaded Pascal programmers.
Good luck
Gordon
Gordon Couger
Biosystems & Agricultural Engineering. 114 AG Hall Stillwater, OK 74075
gcouger@master.ceat.okstate.edu 405 744 8392 day 625-2855 evenings
Here is a farily effecent itoa. Strev can be improved by using
array notation and using the xor trick to swap the chars and
a switch would be quicker than the n+48. I was a long time ago.
Good luck
Gordon
char *strrev(char *s)
{
char t, *end,*begin;
begin = s;
end=s;
while(*end) /* go to end of string */
end++;
*end--; /* back off one */
while (end>s) /* reverse string */
{
t=*s;
*s=*end;
*e=t;
end--;
s++;
}
s=begin;
return s;
}
void itoa(int num, char *s)
#define TRUE 1
#define FALSE 0
{
typedef int boolean; /* boolean data type */
char *cur;
boolean neg = FALSE;
if (num < 0)
{
neg = TRUE;
num = -num;
}
if (num == 0)
{
*s++ = '0';
*s = '\0';
}
else
{
cur = s;
while(num)
{
*cur++ = 48 + (num % 10); /* this could be improved with a switch */
num = num / 10;
}
if (neg)
*cur++ = '-';
*cur++ = 0;
strrev(s);
/* printf("%s\n",s);*/
}
}
Technical Details
Message-ID:
<4g55bi$atc@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4g176b$mrk@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: COUGER GORDON <gcouger@master.ceat.okstate.edu> Newsgroups: comp.lang.c.moderated Subject: Re: NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP? Date: 17 Feb 1996 12:04:34 -0600 Organization: CEAT at Oklahoma State University, Stillwater Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4g55bi$atc@solutions.solon.com> References: <4g176b$mrk@solutions.solon.com> Reply-To: Gordon Couger <gcouger@master.ceat.okstate.edu> NNTP-Posting-Host: solutions.solon.com