Converting between number systems

  • Thread starter Thread starter chaoseverlasting
  • Start date Start date
  • Tags Tags
    Systems
AI Thread Summary
The discussion revolves around converting numbers between different bases and determining the number of digits in the converted number. Participants suggest using logarithmic calculations to estimate the digit count before conversion, specifically the formula log10(X)/log10(base) + 1. There is a focus on the algorithm used for conversion, with one user detailing their approach of collecting remainders in reverse order. A code snippet is provided, which initially had an error in indexing but was corrected. The conversation also touches on existing library functions like `itoa` for base conversion, highlighting the need for understanding both custom implementations and available tools.
chaoseverlasting
Messages
1,050
Reaction score
3
I'm writing a program to convert between the different number systems (from decimal to any base), I know what the general algorithm is and how to implement it. The problem I am facing is, that I don't know how do decide the number of digits in the converted number.

For example, if I were to convert 10 from decimal to binary, I would get 1010, but the number of digits has changed from 2 to 4. How do you decide the number of digits in the new number (1010 in this case).

I know that roughly, if youre changing to a base greater than 10, the number of digits should decrease, and if converting to a base lesser than 10, the digits should increase, but don't know by how much.
 
Technology news on Phys.org
There isn't any general algorithm. I had this for a lab assignment one and I made use of a different algorithm from the one the lab TAs were teaching. My algorithm converted the decimal base from front to back while theirs did the reverse. You should describe how your algorithm is supposed to work before we can help.
 
chaoseverlasting said:
I don't know how do decide the number of digits in the converted number.
Think of a simple formula that can determine the tallest number a given number of digits can hold in any base. For instance for 4 digits in the 10-based system it is 10 * 10 * 10 * 10 - 1 for the binary system it would be 2 * 2 * 2 * 2- 1.
 
Think how logbase(number) relates to the number of digits.
 
Defennder said:
There isn't any general algorithm. I had this for a lab assignment one and I made use of a different algorithm from the one the lab TAs were teaching. My algorithm converted the decimal base from front to back while theirs did the reverse. You should describe how your algorithm is supposed to work before we can help.

Im doing it the only way I know how, whatever number need to be converted is divided repeatedly by the base and the remainders are collected. The collected remainders in the reverse order is the number.

Im collecting the remainders in a dynamic array, and I need to know the size of the converted number to define the size of the array.


Borek said:
Think how logbase(number) relates to the number of digits.

If we use a base 10 number and find log10(number) for it, then because that number can be expressed in powers of 10, then [log10[/number](number)] (where[...] is the greatest integer function) will give us the number of digits -1 because whatever the number, without the powers of 10 its value should always be lesser than 1.
Carrying this forward to other bases, if I convert to binary, then log2(number}2 should give me number of digits of binary -1 right?

The only problem with this is that I need to know the binary number to find its length and I can't initialize the array. How can I find out the length of the number before conversion?

MeJennifer said:
Think of a simple formula that can determine the tallest number a given number of digits can hold in any base. For instance for 4 digits in the 10-based system it is 10 * 10 * 10 * 10 - 1 for the binary system it would be 2 * 2 * 2 * 2- 1.

Why does the -1 come in? I mean I get that 104 would be 5 digits, but is there a more formal reason for it?
 
chaoseverlasting said:
The only problem with this is that I need to know the binary number to find its length and I can't initialize the array. How can I find out the length of the number before conversion?

Number is a number, and its log is its log, doesn't matter if it is decimal, hexadecimal or something else.

Do you know how to convert between logarithms of different bases? Pretty simple operation.
 
Borek said:
Number is a number, and its log is its log, doesn't matter if it is decimal, hexadecimal or something else.

Do you know how to convert between logarithms of different bases? Pretty simple operation.

Yeah, that's not what I meant. What I mean is, that when I am converting between base 10 and any other base, how can I find the length of the number in the other base? Eg, 10 from decimal to binary is 1010, and the length in binary is 4. Before converting, how can I find the length in binary?

The log method will only work after I've found the number out (ie, log21010 =3.something), but I can't use this before converting 10. Thats what I need to do.
 
chaoseverlasting said:
Yeah, that's not what I meant. What I mean is, that when I am converting between base 10 and any other base, how can I find the length of the number in the other base? Eg, 10 from decimal to binary is 1010, and the length in binary is 4. Before converting, how can I find the length in binary?

The log method will only work after I've found the number out (ie, log21010 =3.something), but I can't use this before converting 10. Thats what I need to do.

No! That's not what he's saying at all! 1610= 100002 because 16= 24. It has 5 bits because it is 24 and so is a 1 followed by 4 0s. 1710= 100012 because 17= 24+ 1. It has 5 bits because it is 1 (less than 2) added to 24. Or, more consisely, 16, in base 2 has 5 bits because log2(16)+ 1= 4+1 (the "1" is added for the non-zero bit) and 17, in base 2, also has 5 bits because log2(17)= log10(17)/log10(2)= 4.087... has integer part 4 and 4+ 1= 5.

In general, the number X, in base 10, converted to base a, has log10(X)/log10(a)+ 1 "digits".


For example, the number 1232311, base 10, converted to base 16, has 6 "digits" because log10(1232311)/log10(16)= 5.897... has integer part 5; 6= 5+1. And, in fact, it is easy to show that 123231110= 12CDB716, with 6 "digits".
 
HallsofIvy said:
No! That's not what he's saying at all! 1610= 100002 because 16= 24. It has 5 bits because it is 24 and so is a 1 followed by 4 0s. 1710= 100012 because 17= 24+ 1. It has 5 bits because it is 1 (less than 2) added to 24. Or, more consisely, 16, in base 2 has 5 bits because log2(16)+ 1= 4+1 (the "1" is added for the non-zero bit) and 17, in base 2, also has 5 bits because log2(17)= log10(17)/log10(2)= 4.087... has integer part 4 and 4+ 1= 5.

In general, the number X, in base 10, converted to base a, has log10(X)/log10(a)+ 1 "digits". For example, the number 1232311, base 10, converted to base 16, has 6 "digits" because log10(1232311)/log10(16)= 5.897... has integer part 5; 6= 5+1. And, in fact, it is easy to show that 123231110= 12CDB716, with 6 "digits".

Thank you so much! I was just running around in circles trying to figure that out! That brilliantly explains it!

And thank you Borek and everyone else for helping me along!
 
  • #10
I can't figure out what I am doing wrong. Could someone please tell me where I am going wrong? Here's the code:

Code:
//N-base system conversion program

#include <iostream>
#include <cmath>

using namespace std;

void convert(int , int, int, int*);    //convert(number, base, length, result)

int len=0, i;

int main()
{
    int num, base, *r;
    
    cout<<"\nEnter a number: ";
    cin>>num;
    cout<<"\nEnter base: ";
    cin>>base;
    
    len=(int)log10(num)/log10(base)+1;       //Number of digits of the converted number
    
    r=new int [len];
    
    convert(num, base, len, r);
    
    cout<<endl;
    
    for(i=0; i<len; i++)
    cout<<*(r+i);

    delete [] r;
    
    return 0;
}

void convert(int n, int b, int len, int* res)
{
     for(i=0; i<len; i++)
     {
              *(res+len-i)=n%b;
              n/=b;
     }
}
 
  • #11
Problem solved. Forgot to subtract 1 in statement *(res+len-i). Should be *(res+len-i-1). Stupid mistake.
 
  • #12
Or you can write

for (i = len - 1; i >= 0; i--)

There's no rule that says your FOR loops must count up.
 
  • #13
Are you aware of

Code:
char *itoa( int value, char *string, int radix );

which does exactly what you need? Could be you were asked to write it on your own, but there is already a library version.
 
  • #14
Borek said:
Think how logbase(number)

Is there an obvious way of calculating logbase(number) from log10(number) for any base?
 
  • #15
mgb_phys said:
Is there an obvious way of calculating logbase(number) from log10(number) for any base?

We have known

a = \log_bx

and we need

c = \log_dx

obviously

b^a = x

so

c = \log_db^a = a*\log_db

but you already know a, so you just multiply by logdb and you are ready :biggrin:
 
  • #16
Borek said:
obviously

b^a = x
Only "obviously" if you have itthe right way round!
Somehow I managed to get a^b = x !

thanks - I'm sure that will come in useful one day, not sure when.
 
  • #17
It was much more obvious 30 years ago, when calculators were much more rare then now. Everyone knew how to convert from ln to log10 - by multipliying by 2.303!
 
  • #18
Borek said:
Are you aware of

Code:
char *itoa( int value, char *string, int radix );

which does exactly what you need? Could be you were asked to write it on your own, but there is already a library version.

No actually! This wasnt homework, it was something I wanted to do because I need to use it in another one of my programs. I didnt know there was already something written for it! How do you use that function though?
 
  • #19
Code:
#include <stdio.h>
#include <stdlib.h>

const int iNumber = 123456789;

int main()
{
	char sz[33]; // will be enough for any 32-bit integer
	int iRadix;

	printf("Number %i(dec) is:\n",iNumber);

	for (iRadix = 2;iRadix != 33;iRadix++)
	{
		itoa(iNumber,sz,iRadix);
		printf("base: %2i -> %32s\n",iRadix,sz);
	}

	return 0;
}

Output:
Code:
Number 123456789(dec) is:
base:  2 ->      111010110111100110100010101
base:  3 ->                22121022020212200
base:  4 ->                   13112330310111
base:  5 ->                     223101104124
base:  6 ->                      20130035113
base:  7 ->                       3026236221
base:  8 ->                        726746425
base:  9 ->                        277266780
base: 10 ->                        123456789
base: 11 ->                         63762a05
base: 12 ->                         35418a99
base: 13 ->                         1c767471
base: 14 ->                         12579781
base: 15 ->                          ac89bc9
base: 16 ->                          75bcd15
base: 17 ->                          51g2a21
base: 18 ->                          3b60f89
base: 19 ->                          2bg64ae
base: 20 ->                          1ibc1j9
base: 21 ->                          194gh7f
base: 22 ->                          11l0805
base: 23 ->                           j43jfb
base: 24 ->                           fc2egl
base: 25 ->                           cg15le
base: 26 ->                           aa44a1
base: 27 ->                           8g86ni
base: 28 ->                           74nqb1
base: 29 ->                           60fshj
base: 30 ->                           52ce69
base: 31 ->                           49l302
base: 32 ->                           3lnj8l

Honestly, I don't remember how digits over F are assigned. And it works only for numbers lesser then INT_MAX.

Tried under Visual C.
 
Back
Top