NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP? 
Author Message
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

Greetings -

I'm converting numbers from an input file from decimal to hex, oct, and bin.
The 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.

Thanks,

Charlie ;/)



Tue, 04 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

Quote:

>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
Quote:
>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

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);*/
      }
   }



Wed, 05 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

:Greetings -
:
:I'm converting numbers from an input file from decimal to hex, oct, and bin.
:The 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.

I'm not going to rewrite your code since (a) it could be homework, and
(b) if I did, I'd feel obliged to test it, and that's more time than
I want to spend on this.  But I'll give you some general hints.

Since there is no "write backwards" facility in C, you will
have to determine the first digit before writing anything out.
The usual approach for this is to create a string in reverse order,
and then write out the string when you're done.

Are you dealing with negative numbers?  If so, be careful.

Your problem with hex is the "%i" format.  It always prints in
decimal.  You could use "0123456789ABCDEF"[iCoeff] with "%c".

Final hint: there is a *MUCH* easier way to output in hex and octal,
leaving you only with the binary as a special case.

Cheers,
Stan.
--



Sun, 09 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

Quote:
>Here is a farily effecent itoa. Strev can be improved by using
>array notation and using the xor trick to swap the chars

The `xor trick' is almost always *slower* than swapping via a
temporary.  (If it is *faster* -- as opposed to equally fast --
you can simply improve or replace the compiler.  The compiler should
be able to recognize a swap and code it via xor, if that would be
faster.  Recognizing that a sequence of xors accomplishes a swap,
and replacing it with the [probably faster] swap via temporary, is
a less interesting optimization.)

Incidentally, the fastest way to reverse a string is not to reverse
it.  (The fastest and least-buggy code is that which is not present.)
If you want to print the result of the conversion, you can loop
backwards over the string, or you can simply generate the string in
reverse, e.g.,

        do {
                digit = n % base;
                n /= base;
                *--p = digit + '0';     /* assuming base <= 10 */
        } while (n != 0);

This argues against even having a low-level function like itoa();
or, if such a function is appropriate, it might be best to pass it
a buffer and a size, and have it return a pointer into the buffer
(typically past the beginning).  Passing a size is also wise in case
the number cannot be represented in the buffer, e.g., a six-byte
buffer (and decimal base) for a value that is >99999 or <-9999.

Quote:
>and a switch would be quicker than the n+48. I was a long time ago.

This is relatively unlikely as well -- a switch will probably turn
into a computed goto, which produces pipeline bubbles on modern
processors.

Quote:
>void itoa(int num, char *s)
  ...
>   if (num < 0)
>      {
>      neg = TRUE;
>      num = -num;
>      }

This code fails on 2's complement implementations when num is the
`most negative' number, e.g., -32768 or -2147483648.

(To fix it, use unsigned arithmetic.)

Quote:
>   if (num == 0)

This is unnecessary; simply use a do/while as above.

To allow bases above 10, you might want to code this as, e.g.,

        char *ltostr(long val, char *buf, size_t bufsize, int base) {
                unsigned long u;
                int digit;
                char *p;

                /* Sanity check -- or maybe assert(bufsize >= 2). */
                if (bufsize < 2)
                        return (NULL);

                /* Likewise. */
                if (base < 2 || base > 36)
                        return (NULL);

                /* Change value to an appropriate unsigned for conversion. */
                if (val < u)
                        u = -(unsigned long)val;
                else
                        u = val;

                /* Perform the conversion in reverse. */
                p = buf + bufsize;
                *--p = '\0';
                do {
                        if (p == buf)
                                return (NULL);  /* out of space */
                        digit = u % base;
                        u /= base;
                        *--p = "0123456789abcdefghijklmnopqrstuvwxyz"[digit];
                } while (u != 0);

                /* Add leading sign if necessary. */
                if (val < 0) {
                        if (p == buf)
                                return (NULL);
                        *--p = '-';
                }

                /* Return pointer to leading digit or sign. */
                return (p);
        }

The companion ultostr() function is fairly obvious.

(For optimization purposes, it might [or might not] be profitable
to code {,u}ltostr using signed and/or `int' arithmetic for those
values where `int's suffice.  This should, however, only be tried
if profiling suggests that the inner loop of the conversion is a
bottleneck.)

The choice of alphabet (here, lowercase English/ASCII) may not be
suitable for all applications, but I did not want to get into
locales.
--
In-Real-Life: Chris Torek, Berkeley Software Design Inc



Sun, 09 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?


Quote:
> Greetings -

> I'm converting numbers from an input file from decimal to hex, oct, and bin.
> The 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?

Just an idea, assumes you have an int, the base and an open file.
Beware of the non-existent error checking!

#include <stdio.h>

int i = 6 * 9;  /* should be 42 in base 13 */
int base = 13;

FILE *file = stdout;

main(void){

 char c[32], *p = c;

 do{
   *p++ = "0123456789abcdef" [i % base];
 } while(i /= base);

 do{
   putc(*p,file);
 } while(p-- != c);

 putc('\n',file);

 return 0;

Quote:
}

// Jens M Andreasen


Sun, 09 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?


|> >Here is a farily effecent itoa. Strev can be improved by using
|> >array notation and using the xor trick to swap the chars

|> The `xor trick' is almost always *slower* than swapping via a
|> temporary.  (If it is *faster* -- as opposed to equally fast --
|> you can simply improve or replace the compiler.  The compiler should
|> be able to recognize a swap and code it via xor, if that would be
|> faster.  Recognizing that a sequence of xors accomplishes a swap,
|> and replacing it with the [probably faster] swap via temporary, is
|> a less interesting optimization.)

An even more important reason not to use the xor trick is that it
doesn't work if the values to be swapped are in fact aliases for the
same value.

|> Incidentally, the fastest way to reverse a string is not to reverse
|> it.  (The fastest and least-buggy code is that which is not present.)
|> If you want to print the result of the conversion, you can loop
|> backwards over the string, or you can simply generate the string in
|> reverse, e.g.,

|>   do {
|>           digit = n % base;
|>           n /= base;
|>           *--p = digit + '0';     /* assuming base <= 10 */
|>   } while (n != 0);

|> This argues against even having a low-level function like itoa();
|> or, if such a function is appropriate, it might be best to pass it
|> a buffer and a size, and have it return a pointer into the buffer
|> (typically past the beginning).  Passing a size is also wise in case
|> the number cannot be represented in the buffer, e.g., a six-byte
|> buffer (and decimal base) for a value that is >99999 or <-9999.

I generally use a buffer of `sizeof( long ) * CHAR_BITS + 2' length.
This will handle anything you will generate in any base >= 2.  (Bases
less than two aren't particularly interesting anyway:-).)  The added 2
is for the sign and the trailing '\0'.

I've deleted the rest.  It looked amazingly like the code I generally
use.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils, tudes et ralisations en logiciel orient objet --
              -- A la recherche d'une activit dans une region francophone



Mon, 10 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

[...]

Quote:
>An even more important reason not to use the xor trick is that it
>doesn't work if the values to be swapped are in fact aliases for the
>same value.

I think that I know what you mean by this, but I don't think that
it's what you wrote.  :-)

Cheers,
Stan.
--



Wed, 12 Aug 1998 03:00:00 GMT  
 NUMBER SYSTEM CONVERSION PRINTS BACKWARDS - HELP?

Quote:
Ryckman) writes:



|> [...]
|> >An even more important reason not to use the xor trick is that it
|> >doesn't work if the values to be swapped are in fact aliases for the
|> >same value.

|> I think that I know what you mean by this, but I don't think that
|> it's what you wrote.  :-)

Reading it above, I'm not sure I even understand what I actually wrote.
What I meant to say, of course, is that if the two pointers passed into
swap point to the same object, the xor trick does not work.
--

GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils, tudes et ralisations en logiciel orient objet --
              -- A la recherche d'une activit dans une region francophone



Tue, 18 Aug 1998 03:00:00 GMT  
 
 [ 8 post ] 

 Relevant Pages 

1. need help in number conversions

2. function: representation of a number in any number system

3. binary number systems in C data types HELP!

4. Beginner needs help to print binary number

5. Help-- Array-- print subscript of max number

6. Help: How to print Hex numbers

7. HELP: How to print page number in CRichEditView??

8. Question : Print & Print Preview Page Numbers

9. paging backwards in a file...? help

10. String/Number Conversion

11. text file conversion to array of numbers

12. Code for conversion of decimal to IEEE number?

 

 
Powered by phpBB® Forum Software