I'm trying to find a way to convert a number in any given base to decimal and then to the target base. What i'm asking is how will I represent this procedure in the function for example 123 base 4 to decimal= 1x4^2+2x4^1+3x4^0=27. I was thinking of decrementing the raised power with a for statement.But i'm also using a for statement to access each number in the string array. heres my attempt

#include<stdio.h>

int main(void)

{
	char num_string;
	int sourcebase;
	int targetbase;
	int temp

	do {
		printf("Enter a positive number/n");
		scanf_s("%c",&num_string);
		printf("Enter the base of that number");
		scanf_s("%d", &sourcebase);
		printf("Enter the destination base");
		scanf_s("%d",&targetbase);
		if((sourcebase<2)||(sourcebase>10)){
		printf ("You number is invalid!!!!!!!/n/n");
	}
	}
     length= //some code to get string length

   for(i=0;i<length,i++)

   temp=num_string[i]*sourcebase //here should be corresponding index

Recommended Answers

All 24 Replies

You actually wanted num_string as char array( C style string) but have declared it as being char which will hold only one character.

char num_string = '\0' ; // wrong
char num_string[BUFSIZ] = {'\0'} ; // correct, will now hold a number string

Also can you give a sample output your program is supposed to display, since it would help in clearing hte problem stmt which is not so apparent to me, seeing your imcomplete implementation.

Ok the program is supposed to convert to the target base of a number given the soucre base and the number. I am using decimal as a segway between bases after I get to decimal I'll divide out using the target base.

Enter a positive number : 120
Enter the base of that number (2 to 10) : 3
Enter the target base (2 to 10) : 5
The number in the target base is : 30

Okay I will give you the algorithm, you just try to implement it.

  • Accept the number, the source base and the target base from the user.
  • convert the given "number" having base "source_base" into decimal using the formula:
while( tmp_number )
    {
        decimal += (tmp_number % 10) * pow( source_base, i ) ;
        tmp_number /= 10 ;
        ++i ;
    }
  • Now we have the decimal equivalent of the number in "decimal"
  • Create a dynamic array uisng pointer to int which will hold the individual digits of the new number of the target base.
  • Using the given formula convert from decimal to your base.
while( decimal )
    {
        new_number[i] = decimal % target_base ;
        decimal /= target_base ;
        new_number = (int*) realloc( new_number, i + 2 ) ;
        ++i ;
    }
  • In the end you would get your required number by traversing through the integer array.

Hope it helped, bye.

Does this negate the need for the for statement?How will it know which digit to multippy the base and exponent by?

while constructs and for constructs are both looping constructs -- you can use either one of them for looping purpose if thats what you wanted to ask. decimal += (tmp_number % 10) * pow( source_base, i ) ; Here decimal is the var which will hold the decimal value of the entered number with the base "source_base". To it we iteratively add the digit * source_base ^ i.

Here digit is obtained by doing tmp_number % 10 while i controls the exponent value.

ok (last question i swear )so when we say while(temp_number) when are we telling the loop to terminate? shouldn't we say
while(temp_number%10 !=0)?

while (temp_number) means continue with the loop while temp_number is not 0. Inside the loop I am dividing the temp_number with 10 ( temp_number /= 10 ) so the loop ends when this value reaches 0.

eg.
Initial value = 129
129 / 10 = 12
12 / 10 = 1
2 / 10 = 0 ( loop ends )

Hope it made matters a bit clear for you.

what is the realloc() doing here and why are we adding 2?I've never used it before
new_number = (int*) realloc( new_number, i + 2 ) ;

Hmmm... realloc is the memory management function which really makes the job of dynamic memory allocation actually "dynamic".

Dynamic memory when allocated using malloc , returns a pointer to the allocated peice of memory or memory block. But if the user wants to dynamically increase the size of the memory allocated to the same pointer, malloc wont do hte job.

To expand or to allocate more memory to the pointer which already has been allocated memory using malloc , we use realloc ( reallocation of memory ).

Consider this snippet:

// result stored in the dynamically allocated integer array with
// one slot
    int* new_number = (int*) calloc( sizeof( int ), sizeof( int ) ) ;

    i = 0 ;
    while( decimal )
    {
        new_number[i] = decimal % target_base ; 
        decimal /= target_base ;

        new_number = (int*) realloc( new_number, i + 1 ) ;
// we need more memory, which will be controlled by the counter i 
// hence while reallocing we use i as reference. So when i = 1
// allocate (2 + 1) = 3 slots and so on.

        ++i ;
    }

realloc takes two arguments, the first one being the pointer which has to be reallocated memory and the second one being the new size of the memory to be allocated.

For more info look here:
http://www.cplusplus.com/ref/cstdlib/realloc.html

Hope I have been helpful , bye.

Ok, i'm getting an error on this line
new_number = (int*) realloc( new_number, i + 2 )

error C2440: '=' : cannot convert from 'int *' to 'int [1]' i am using the correct data types

Hmm please post your entire code so that i can have a look at it. My best guess is that you have declared new_number as an array of integers, which should actually be an integer pointer.

You must have done: int new_number [4] ; But you should have done: int* new_number = NULL ; Post your code which shows what you have done so far.

Now i can't get out of my loop heres the code but I warn you its pretty sloppy and i'm getting some warnings.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>

int main(void)

{
	
	long double sourcebase;
	int targetbase;
                int tmp_number;
	int* new_number = NULL;

	do {
		printf("Enter a positive number\n");
		scanf_s("%d",&tmp_number);
		printf("Enter the base of that number\n");
		scanf_s("%d", &sourcebase);
		printf("Enter the destination base");
		scanf_s("%d",&targetbase);
		if((sourcebase<2)||(sourcebase>10)){
		printf ("You number is invalid!!!!!!!\n\n");
	}
	

	}
 while( tmp_number );
 int i=0;
 int decimal=0;
    {
        decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
        tmp_number /= 10 ;
        ++i ;
    }

while( decimal )
 int decimal=0;
    {
        new_number[i] = decimal % targetbase ;
        decimal /= targetbase ;
        new_number = (int*) realloc( new_number, i + 2 ) ;
        ++i ;
    }

printf("You number is:%d",new_number);
	

return 0;
	}
int main(void)
{
    long double sourcebase; 
// why long double, why not just long or
//  int. long is sufficient for your needs.
// also initialize variables as you declare them to avoid bugs

     int targetbase = 0; // initialize variables, good practice
    int tmp_number = 0;
    int* new_number = NULL;
    int  flag = 0 ; // to check whether number entered is valid or not

    // pull stmts which dont require validataion out of loop
    printf("Enter a positive number: ");
    scanf_s("%d",&tmp_number);
    printf("Enter the destination base: ");
    scanf_s("%d",&targetbase);

    do 
   {
        flag = 0 ;
        printf("Enter the base of that number: ");
        scanf_s("%d", &sourcebase);

        if( (sourcebase<2) || (sourcebase>10) )
        {
             printf ("You number is invalid!!!!!!!\n\n");
             flag = 1; 
         }
    }
   while( flag );

 int i=0;
 int decimal=0;

while( temp_number ) // you forgot something ?
    {
        decimal += (tmp_number % 10) * pow( sourcebase, i ) ;
        tmp_number /= 10 ;
        ++i ;
    }


//  int decimal=0; // remove this since this will reset the decimal value we just calculated

 while( decimal )
    {
        new_number[i] = decimal % targetbase ;
        decimal /= targetbase ;
        new_number = (int*) realloc( new_number, i + 2 ) ;
        ++i ;
    }

 // printf("You number is:%d",new_number);
// The above is the incorret way of printing values of an array
// Loop through the various elements like
// eg. long* my_array = {1, 2, 3, 4} ;
// for( .... )
// { print values }
    
return 0;
    }

I hope you are understanding the things I have written, because if you dont then there is no point in completing the exercise, if you dont gain any knowledge.

BTW i am logging off and would be away for 6 hrs, so post any further problems you have got and if they are unanswered I will answer them later.

Okay i modified the code. My question is how do place the remainder figures in the new number string?

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>


int main(void)
{		
	/* Initialization section*/

	char number[50];
	char new_number[50];
	int sourcebase=0;
	int targetbase=0;
	int length=0;
	int decimal=0;
	int power=0;
	int remainder=0;
	
	
	do { 
			/* Get user information*/
			system("cls");
		printf("Enter a source base between 2 and 10:");
		scanf_s("%d",&sourcebase);
		if((sourcebase<2||sourcebase>10)){
		printf("Invalid!!!Your source base must be between 2 an 10\n\n");
			system("pause");
	    continue;
		}
		printf("Enter a positive number:");
		scanf_s("%s",number,49);

		length=strlen(number);

		for(int i=0;i<length;i++){
			if((number[i]<'0')||(number[i]>=sourcebase+'0')){
			printf("Error!!! number cannot be less than zero.\n\n");
				system("pause");
		break;
			}
		
				if (i<length) continue;
		}
		printf("Enter a target base between 2 and 10:");
		scanf_s("%d",&targetbase);
		if((targetbase<2||targetbase>10)){
		printf("Invalid!!!Your target base must be between 2 an 10\n\n");
			system("pause");
		continue;
		}
		break;
		/* Validate User Data*/
	}while(1);
	   /* Convert to Decimal*/
	for (int j=length-1; j>=0;--j){
		decimal+=(number[j]-'0')*pow((float)sourcebase,power);
		power++;
		
	} int k=0;

       while(decimal>0){

	   /* Convert to Target Base*/
     
          remainder=decimal%targetbase;
          decimal=decimal/targetbase;
		  new_number[k]=('0' + remainder);
		  --k;// I tried here but it prints garbage

  
          }
	   /* Display Converted Number*/

  printf("Your number is:%s\n\n",new_number);

	return 0;
}
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>


int main(void)
{        
    /* Initialization section*/

    char number[50] = { '\0' } ; // Initialize MUST
    char new_number[50] = { '\0' } ; // Initialize MUST
    int sourcebase=0;
    int targetbase=0;
    int length=0;
    int decimal=0;
    int power=0;
    int remainder=0;
    
    
    do { 
           system("cls"); // dont use OS dependent funcitons

         printf("Enter a source base between 2 and 10:");
        scanf_s("%d",&sourcebase);
        if((sourcebase<2||sourcebase>10)){
        printf("Invalid!!!Your source base must be between 2 an 10\n\n");
             system("pause"); // dont use OS dependent functions
        continue;
        }
        printf("Enter a positive number:");

        scanf_s("%s",number,49); // dont know what it does
// it is not a standard C function.
 
        length=strlen(number);

        for(int i=0;i<length;i++){
            if((number[i]<'0')||(number[i]>=sourcebase+'0')){
            printf("Error!!! number cannot be less than zero.\n\n");
                system("pause");
        break;
            }
        
                if (i<length) continue;
        }
        printf("Enter a target base between 2 and 10:");
        scanf_s("%d",&targetbase);
        if((targetbase<2||targetbase>10)){
        printf("Invalid!!!Your target base must be between 2 an 10\n\n");
            system("pause");
        continue;
        }
        break;
        /* Validate User Data*/
    }while(1);
       /* Convert to Decimal*/
    for (int j=length-1; j>=0;--j){
        decimal+=(number[j]-'0')*pow((float)sourcebase,power);
        power++;
        
    } 

// int k=0; 
// WRONG !! if you want to add the remainder at the end of the
// character array you should initilize it with the last index of teh 
// character array and not 0

// Also adding remainder at the end of the array is difficult
// to achieve since the start positions of the char array might go
// wasted and print out junk while printing out the whole array.

// Better start appending the remainder at the start of char array.

       while(decimal>0){

       /* Convert to Target Base*/
     
          remainder=decimal%targetbase;
          decimal=decimal/targetbase;
          new_number[k] = ('0' + remainder) ;
          --k;// I tried here but it prints garbage

  
          }
       /* Display Converted Number*/

  printf("Your number is:%s\n\n",new_number);

    return 0;
}

I have pointed out some problem areas.. get them corrected and then repost.

int main(void)
{		
	/* Initialization section*/

	char number[50]={ '\0' };
	char new_number[50]={ '\0' };
	int sourcebase=0;
	int targetbase=0;
	int length=0;
	int decimal=0;
	int power=0;
	int remainder=0;
	
	
	do { 
			/* Get user information*/
			system("cls");// is there anything else i can use to clear the screen
		printf("Enter a source base between 2 and 10:");
		scanf_s("%d",&sourcebase);
		if((sourcebase<2||sourcebase>10)){
		printf("Invalid!!!Your source base must be between 2 an 10\n\n");
			system("pause");
	    continue;
		}
		printf("Enter a positive number:");
		scanf_s("%s",number,49);I use scanf_s because my express compiler complains with scanf

		length=strlen(number);

		for(int i=0;i<length;i++){
			if((number[i]<'0')||(number[i]>=sourcebase+'0')){
			printf("Error!!! number cannot be less than zero.\n\n");
				system("pause");
		break;
			}
		
				if (i<length) continue;
		}
		printf("Enter a target base between 2 and 10:");
		scanf_s("%d",&targetbase);
		if((targetbase<2||targetbase>10)){
		printf("Invalid!!!Your target base must be between 2 an 10\n\n");
			system("pause");
		continue;
		}
		break;
		/* Validate User Data*/
	}while(1);
	   /* Convert to Decimal*/
	for (int j=length-1; j>=0;--j){
		decimal+=(number[j]-'0')*pow((float)sourcebase,power);
		power++;
		
	} int k=0;// how do i initilize k with the last index

       while(decimal>0){

		   k+=1;

	   /* Convert to Target Base*/
     
          remainder=decimal%targetbase;
          decimal=decimal/targetbase;
		  new_number[k]=('0' + remainder);//Explain what u mean by "appending the remainder at the start" 
		  --k;

Huh !!! What is the question ?
If you want to point out somethign in the code, highlight it so that i can know.

sorry...
>>system("cls");// is there anything else i can use to clear the screen?

>>scanf_s("%s",number,49);I use scanf_s because my express compiler complains with scanf

>>} int k=0;// how do i initilize k with the last index
new_number[k]=('0' + remainder);//Explain what u mean by "appending the remainder at the start"

>>system("cls");// is there anything else i can use to clear the screen?

No, there is as such no standard way to clear the screen. It is always compiler or OS dependent. So use it if you want, but your code will not be cross platform complaint.

I use scanf_s because my express compiler complains with scanf

Let it complain. scanf_s is not a standard C function.

new_number[k]=('0' + remainder); //Explain what u mean by "appending the remainder at the start"

What i mean is that:

You have a character array new_variable[50] = { '\0' } ; Now what you want to do is to extract out the remainder from the decimal number and convert it into a string.

while(decimal>0){

       /* Convert to Target Base*/
     
          remainder=decimal%targetbase;
          decimal=decimal/targetbase;
          new_number[k] = ('0' + remainder) ;
          --k;// I tried here but it prints garbage

  
          }

Instead of this, initialize k as k = 0 and start appending the remainder at teh start with something like:

int k = 0 ;

while(decimal>0)
{
   remainder=decimal%targetbase;
   decimal=decimal/targetbase;
   new_number[k] = ('0' + remainder) ;
   ++k ;
}

And display the number by looping through the array:

for( int i = 0; i <= k; ++i )
   // display each character

I works great except the remainders are backward How can i reverse the string?

edit* sorry i know i'll use the loop Thanks for everything

No need to actually reverse the string -- unless your application demands so. Just traverse the array backwards using the for loop and everything should work out to be fine.

int string_length = strlen( number ) ;
for( int i = string_length - 1; i >= 0; --i )
{
    // output chars
}
int string_length = strlen( new_number ) ;

	  for( int l = string_length - 1; l >= 0; --l ){

  printf("Your number is:%s\n\n",new_number[l]);
	  }
	return 0;

gives me an error is it the way i am printing?

When I said printing out the individual elements of the character array, you should use the qualifier %c instead of %s in your print statement, since array elements are characters and not character pointers.

int string_length = strlen( new_number ) ;

      for( int j = string_length - 1; j >= 0; --j ){

  printf("Your number is:%s",new_number[j]);
      }
    return 0;

gives me an error is it the way i am printing?

It works! thankyou

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.