mohelli5's blog

By mohelli5, 11 years ago, In English

hi , i have a little problem in chaniging the base of a number from ten to 4 if someone here can write the code it will be helpful in qbasic or c++ plz thanks

  • Vote: I like it
  • -8
  • Vote: I do not like it

»
11 years ago, # |
Rev. 5   Vote: I like it +3 Vote: I do not like it

The algorithm of converting a decimal number to any base is quite easy. suppose the number is N and the desired base is B ,then algorithm goes like this: We take an array to keep the remainder and also to print result and we also take a variable 'index' to fix the index in the array ==>

arr[100010],index=0;
while  N does not become zero -> 
[
1.ara[index++]=N%B
2. N=N/B
]
Reverse the array and print it.
Or print the array from last to start.

<== Here is my code: -------------------->

#include<stdio.h>
#include<iostream>
using namespace std;
int ara[10010],index=0;
int main()
{
    int N,B;
    cin>>N>>B;
    while(N!=0)
    {
        ara[index++]=N%B;
        N=N/B;
    }
    for(int i=index-1;i>=0;i--) cout<<ara[i];
    cout<<endl;
}

<---------------------------- You can use itoa function to do it faster but remember it is not supported by GNU compiler. But what the hell??! You can though use it to debug any code very fast. Here is a reference to itoa function http://www.cplusplus.com/reference/cstdlib/itoa/ :) :)