Click here to Skip to main content
14,241,248 members

Convert to base in C

steve NN asked:

Open original thread
Hello,

I'm new in the field. Unfortunately I don't understand the third function in this program I want to know what do
for(--digit; digit >= 0; --digit )

and
baseDigits[nextDigit]
.

Thank you.

What I have tried:

#include <stdio.h>
int convertedNumber[64];
long int numberToConvert;
int base;
int digit = 0;
void getNumberAndBase (void)

{
        printf ("Number to be converted? ");
        scanf ("%li", &numberToConvert); printf ("Base? "); scanf ("%i", &base);
        if ( base < 2 || base > 16 ) {
          printf ("Bad base - must be between 2 and 16\n"); base = 10; }
}
void convertNumber (void) {
        do { convertedNumber[digit] = numberToConvert % base;
             ++digit;
             numberToConvert /= base;
           }
              while ( numberToConvert != 0 );


}
void displayConvertedNumber (void) {
        const char baseDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int nextDigit;
        printf ("Converted number = ");
        for (--digit; digit >= 0; --digit )
        {
          nextDigit = convertedNumber[digit];


          printf ("%c", baseDigits[nextDigit]);
        }
        printf ("\n");

}
int main (void) {
        void getNumberAndBase (void), convertNumber (void), displayConvertedNumber (void);
        getNumberAndBase ();
        convertNumber ();
        displayConvertedNumber ();
        return 0;
}
Tags: C

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100