Well, the idea of ββSOF is to help people think, and not solve their homework, so I will describe this code that I did in C, you can translate it into java, if you want, it is important that you understand how the algorithm works.
1.- I declare some variables i (counter), base (new base 2-16), word[ 32 ] (an array with 32 elements (0-31) here we will store the new number) and number (the number that the user wants to convert )
2.- I enter the values ββfor number and base .
3.- I call the wordCalculator function (here I calculate the new number), this function has 3 arguments (word, number and base), with the prototype of the function you can see that I use the pointer to the word as a real argument (because I will edit the array values )
3.1.- Inside this function (it can be a class method in java), I declare 3 new local variables: result (which takes the value of the number), i (counter) and difference (this will be used in the operation), but how the conversion works ?
/* Example: 125(10) -----> ?(2) 125 |_2 -1- 62 |_2 -0- 31 |_2 -1- 15 |_2 -1- 7 |_2 -1- 3 |_2 -1- 1 */
So, in this example, the binary number for 125 (10) is 1111101 (2), and this is the process that I describe in my function.
3.2.- I calculated% of the whole division and saved it in difference , then divided the result into base (its numerical copy) and loaded it into (this is the link to the next step), after this operation I save the difference in the first location of the word of the array [] (to which the pointer *(word + i) refers *(word + i) , i represents the offset), if the result gives a number below the base, the operation is completed, and the last digit is stored in the array (this is if ( result < base ) ) ..
int wordCalculator( int * const word, long int number, int base ); int main( void ) { int i, base; int word[ 32 ]; unsigned long int number; printf( "Enter the decimal number to be converted: " ); scanf( "%ld", &number ); printf( "\nEnter the new base: " ); scanf( "%d", &base ); i = wordCalculator( word, number, base ); printf( "The number is: " ); for(; i >= 0; i--){ if ( word[ i ] <= 9) printf( "%d", word[ i ] ); else printf( "%c", ( 65 - 10 + word[ i ] ) ); } printf( "\n" ); } int wordCalculator( int * const word, long int number, int base ) { unsigned long int result = number; int i, difference; i = 0; do{ difference = result % base; result /= base; *( word + i ) = difference; i++; if ( result < base ) *( word + i ) = result; } while( result >= base ); return i; }