Computing.Net > Forums > Programming > function to convert between bases

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

function to convert between bases

Reply to Message Icon

Name: geohoffman49431
Date: February 15, 2006 at 23:34:09 Pacific
OS: na
CPU/Ram: na
Product: na
Comment:

Just wondering what is a good general algorithm to convert from base 10 to any base? Does not need to be computer language specific - just the algorithm. It is for a class project. I think the teacher said the algorithm is something like this:


void convert (int number, int base, int result[60])
{
int index = 59;

while ( num >= base )
{
result[index] = number%base;
num = int(num/base);
index--;
}

backwards[index-1] = num;

}

does that look right? I have to write the numbers into the array backwards (starting with the last index) because when you do the first modulo operation you get the low order number first.



Sponsored Link
Ads by Google

Response Number 1
Name: Mechanix2Go
Date: February 15, 2006 at 23:49:02 Pacific
Reply:

"Does not need to be computer language specific"

Then I would start with pseudo code.


If at first you don't succeed, you're about average.

M2


0

Response Number 2
Name: geohoffman49431
Date: February 16, 2006 at 02:39:58 Pacific
Reply:

Naw what I meant was that if you have an algorithm you want to show me it does not need to be language specific. In fact I would preffer a pseudo code explaination over an actual function that just does everything for me. The project I am turning in definitely has to be done in c and compiled with the g++ compiler on our campus server. I can take pseudo code and turn it into c. So if you have an alternate way of doing a base conversion I would like to hear it. I think the code I have above is probably correct - I just cant test it right at the moment cause I am not at home.


0

Response Number 3
Name: Mechanix2Go
Date: February 16, 2006 at 03:18:07 Pacific
Reply:

OK

I don't have an algorithm. Probably others have.

Seems like having someobe hand you one defeats the learning exercise.

Since you think your code will work, download the free Borland Turbo c++

http://bdn.borland.com/article/0,1410,21751,00.html



If at first you don't succeed, you're about average.

M2


0

Response Number 4
Name: StuartS
Date: February 16, 2006 at 04:24:34 Pacific
Reply:

Do a search on Goggle. The Internet is littered with base conversion algorithms.

There is no one algorithm that will do all conversions. You need a different one for each conversion.

Stuart


0

Response Number 5
Name: geohoffman49431
Date: February 16, 2006 at 07:17:41 Pacific
Reply:

I only need to convert from base 10 to any other base. For instance I wont have any base 4 to other base conversions. Also it is not hard to make a conversion from any base to any base. If the starting base is not base 10 then all you do is write a function that converts from any base to base 10 (easy) and then convert from base 10 to any base.

so for example to convert from base 5 to base 9 you convert from base 5 to base 10 then to base 9. There are faster ways to convert if you are going from say a base 2 to base 4 or base 4 to base 16 but they are not general purpose algorithms.

"Seems like having someobe hand you one defeats the learning exercise."

I did not ask for someone to do the work for me. That is why I said I wanted the pseudo code version so I could understand it. I pretty much think my algorithm will work but I am always interested in other ways to do things so that is what I was wondering.


0

Related Posts

See More



Response Number 6
Name: StuartS
Date: February 16, 2006 at 07:53:20 Pacific
Reply:

There is nothing in your algorythm that will convert from base 10 to base 2 (binary) or from base 10 to base 16 (Hexidecimal) which is what I suspect your tutor is after.

>> from any base to base 10 (easy) <<

Is it? Try converting F5A3 to base 10 or 10011011 to base 10.

Stuart


0

Response Number 7
Name: geohoffman49431
Date: February 16, 2006 at 08:11:34 Pacific
Reply:

F5A3 = F*16^3 + 5*16^2 + A*16^1 + 3*16^0 = 15*16^3 + 5*16^2 + 10*16^1 + 3*16^0 = 15*4096 + 5*256 + 10*16 + 3*1 = 61440 + 1280 + 160 + 3 = 62883

10011011 = 1*2^7 + 0*2^6 + 0*2^5 + 1*2^4 + 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0 = 128 + 16+ 8+ 2 + 1 = 155

easy to do. easy formula. easy to impliment.


The formula is just this:

assume the number you want to convert has n characters. So the high order character is at index n-1.

number[n-1]*base^(n-1) + number[n-2]*base^(n-2) + ... + number[0]*base^(0)



0

Response Number 8
Name: geohoffman49431
Date: February 16, 2006 at 08:14:12 Pacific
Reply:

also do you even program? Cause my algorithm is working for me to convert form base 10 to any other base including 2 and 16 - though I have no clue as to why they would be any different than any other base.


0

Response Number 9
Name: StuartS
Date: February 16, 2006 at 08:41:22 Pacific
Reply:

I have yet to see any computer that will do mathematical calculations on letters. And there lies the problem. Just how do you multiply F by 16.

If you algorithm is working, why are you asking for help.

The formula my look fine on paper, but converting it into an algorithm that the computer can understand is another matter.

Stuart


0

Response Number 10
Name: geohoffman49431
Date: February 16, 2006 at 10:34:09 Pacific
Reply:

hmm because F is a number? A=10, B=11, C=12, D=13, E=14, F=15, G=16, H=17, I=18 .....

it is easy to convert from a set of characters to their numerical equivalents.

int ch_to_i(char ch)
{
if (ch > 64 && ch < 91) return (int)(ch-55);
return (int)(ch-48);
}

ch_to_i(number[n-1])*base^(n-1) + ch_to_i(number[n-2])*base^(n-2) + ... + ch_to_i(number[0])*base^(0)

If you reread my post I originally posted because I was curious if there were any alternative algorithms anyone knew of.


0

Response Number 11
Name: geohoffman49431
Date: February 16, 2006 at 10:37:03 Pacific
Reply:

"I have yet to see any computer that will do mathematical calculations on letters"

I have yet to see a computer that will perform calculations on decimal digits. Sorry, they work in binary. The compiler converts everything to base 2 when you compile.

Feel free to never respond to another of my posts Stewie. K bye now.


0

Response Number 12
Name: StuartS
Date: February 16, 2006 at 11:10:16 Pacific
Reply:

>> I have yet to see a computer that will perform calculations on decimal digits. <<

They all do. They are numbers, not letters.

>> The compiler converts everything to base 2 when you compile. <<

That is true but the compiler has to understand decimal numbers in the first place. You cannot convert a letter to it's binary representation, do a calculation with it and expect a meaningful answer.


Makes note:

Ignore geohoffman49431 in future. He is totally incapable of discussing a problem with resorting to personal abuse, especially when he thinks he is right when in fact he is talking total crap.

argumentum ad hominem

Stuart


0

Response Number 13
Name: geohoffman49431
Date: February 16, 2006 at 22:34:25 Pacific
Reply:

If you believe what you just said then good luck as a programmer. Computers are composed of logical gates which are basically transistors and resistors. So when a program is compiled everything must end up in machine code which is a bunch of on off states. There fore when you talk about low level circuitry the only thing a computer understands is ones and zeros or binary. So when a compiler converts from text to machine code it has to take all those decimal numbers you typed in your program and convert them into binary. That being said there are 2 types of representation - internal and external. internally the computer only saves data as ones and zeros. Externally we see these as a string of characters. So if I say convert "AFGER" into base 3 it is possible as long as you know that the A represents 10, the F represents 15, the G represents 16 etc. That being said when you write a number in a compiler in decimal it is saved as a string of text. When it is compiled the string of text is converted into its binary equivalent and machine code is generated. So from a theoretical stand point there is no difference beween converting a string of text with possible symbols 0-9 and converting a string of text with possible symbols {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,...,X,Y,Z}. It is entirely theoretically possible to make a compiler that does not accept decimal numbers but only say base 24 numbers. There would be no point though because most people cant easily work with base 24 numbers.

Also, I never said the input into a function to convert form any base to any base would be a decimal number. The number to be converted in such a function would have to be a string of characters. The function would then have to convert each character into its decimal equivalent. What I had said was convert each character into the integer it represents. This is what my function char_to_int does. So A would not be converted into 65(base10) or 1000001(base2). It would be converted into 10 which is what my ch_to_int function does (takes each letter A-Z and subtracts 55 because A is 65 in ascii - takes all other integers 0-9 and subtracts 48 because 0 is 48 in ascii - then the number is cast from a character into an integer).

If you think about what I have said then you will realize everything I said in each post makes sense. I will post my algorithm and show you it is possible.


0

Response Number 14
Name: geohoffman49431
Date: February 16, 2006 at 22:39:54 Pacific
Reply:

So you are saying this is not possible?


[code]
#include <iostream>
#include <string>
using namespace std;


int char_to_int(char ch)
{
if (ch > 64 && ch < 91) return (int)(ch-55);
return (int)(ch-48);
}


int convert_any_base_to_decimal(string number,unsigned base)
{
int total = 0;
int sign = 1;
int multiplier = 1;


//find out if it is negative
if (number[0] == '-')
{
sign = -1;
number = number.substr(1,number.size()-1);
}

if (number[0] == '+')
{
number = number.substr(1,number.size()-1);
}


//convert the number
for(int count = number.size()-1; count >= 0; count--)
{
//convert each index to correct decimal value

int cur_char = char_to_int(number[count]);


//if any character is not in the valid for this base return
//example in base 4 valid characters are 0,1,2,3
//invalid chars are 4,5,6,7,8,9,A,B,...,Z
if (cur_char >= base)
{
cout << "charcter \'" << number[count] << "\' is not valid in base " << base << endl;
return 0;
}

total += cur_char*multiplier;
multiplier *= base;
}

return total*sign;
}

int main()
{
int base = 0;
string number = "";

while (base != -1)
{
cout << "base:";
cin >> base;
cout << "number:";
cin >> number;

cout << convert_any_base_to_decimal(number,base) << endl << endl;
}

return 0;
}


[/code]



0

Response Number 15
Name: Wolfbone
Date: February 16, 2006 at 23:21:27 Pacific
Reply:

geohoffman49431: There's really no point - as you may have noticed, this is a math/comp. sci. free zone ;-) On the matter of alternative algorithms, I don't know of any that are substantially different in approach than that which you've already outlined. Perhaps there is something in Knuth. An alternative in form, rather than substance, might look something like this (in elisp):

(defun dec2base (number base)
(let ((syms "0123456789ABCDEFGHIJKLMHNOPQRSTUVWXYZ"))
(cond ((< number base) (string (elt syms number)))
(t (concat (dec2base (/ number base) base)
(string (elt syms (% number base))))))))

Hopefully that's short and simple enough to understand even though the visible structure is lost (if you can paste it into an emacs buffer, you can restore it). The only difference is that it is recursive and uses indexing into an array of symbols.


0

Response Number 16
Name: Sci-Guy
Date: February 16, 2006 at 23:24:48 Pacific
Reply:

I think you made a big mistake in wishing an established programmer good luck in programming.

"hmm because F is a number? A=10, B=11, C=12, D=13, E=14, F=15, G=16, H=17, I=18 ....."

Yes, F is hexadecimal for 15, but as far as I know, G, H, I,...etc., are not a part of the base 16 system.

If you belive they are, good luck in programming.

Please let us know if you found someone's advice to be helpful.


0

Response Number 17
Name: geohoffman49431
Date: February 17, 2006 at 01:08:37 Pacific
Reply:

Thank you Wolfbone for the first response that is helpfull. I will look it over. Many message boards seem to drop the leading tabs and spaces for some reason - maybe to save space. Some allow you to put code inside tags and preserve witespace. That is why I tried to put my code in [code][/code] brackets. Guess it doesnt work here. =(

Sci guy - how else would you represent a number in a base greater than 16? A - Z are just symbols (just like 0-9 are just symbols). You could use any symbol to represent a number. You could say carrot-apple-banana-guacamole is equal to 1324 if you want. Then you could define rules for manipulating these symbols like carrot plus banana equals apple. What you would end up with is a math system exactly like the one we use except the symbols are different.

if y=x^(apple)

then y'=dy/dx=(apple)x^(banana)

It is no coincidence that our math system is base 10 and we have 10 fingers. If we had 17 fingers our math sysem would be base 17, probably. Im sorry I mean base H.

Anyway my computer science proffesor seems to believe that G can equal 16, H can equal 17 and Z can equal 35. Maybe I should tell him some random guy on line thinks he is wrong?

This is the project which specifically states that bases above 10 should be expressed as (A-Z). Also it says in my textbook that it is standard practice to use A-Z when using bases greater than 10.

http://www.cse.msu.edu/~cse320/Projects/project04

I would be curious to know in what way stuart is an established programmer? Just because he can figure out how to post a message on a messageboard and give unhelpfull answers does not establish him. And no matter how established he might be I have never seen him give a usefull answer on any of these forums - and I have seen his name a lot. So he doesnt know an answer to a question he should not post an answer.



0

Response Number 18
Name: Wolfbone
Date: February 17, 2006 at 02:49:26 Pacific
Reply:

I should've done this in the first place:

http://paste.lisp.org/display/16896


0

Response Number 19
Name: geohoffman49431
Date: February 17, 2006 at 04:11:26 Pacific
Reply:

Thanks wolfbone. I never looked at emacs-lisp before tonight but I think I get the gist of it. I looked up an elisp manual and it is not a difficult language to understand. Just Lots of Insignificant Silly Parentheses ;). I like your idea to use recursion. Also your integer to character maping is a much beter one than mine, I think I'll steal that idea ;). I shoulda done it that way to begin with, instead I was using a function with a switch statement like:

char int_to_char(int number)
{
switch (number)
{
case 1: return '1'
case 2: return '2'
.....
case 35: return 'Z'
}
}

My way was way to verbose. Also, In the original post I should have had the third paramater as char result[] instead of int result[]. I realized that after I actually started writing the program code in Visual Studio.


The paste makes the code easier to understand. Only one question - t is the constant for true right? It is the only thing I think makes sense but I could not find documentation on it off of google.


Correct me if I am wrong but this is more or less the c++ equivalent I think:


const string symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

string dec2base (int number, int base)
{
if (number < base) return symbols.substr(number,1);
else return dec2base(number/base, base) + symbols.substr(number%base,1);
}

well anyway the above code does the job. I already turned the project in last night and did it a different way. But I am a nerd so I like to see different ways to tackle different problems thanks for the insights wolf.


0

Response Number 20
Name: Wolfbone
Date: February 17, 2006 at 04:47:39 Pacific
Reply:

Hmm.. I see the links to the elisp documentation at paste.lisp.org aren't working...

Yes, 't' means true and your c++ code is indeed the equivalent - except that I should've used defconst to define the symbol string outside of the defun too.


0

Response Number 21
Name: Wolfbone
Date: February 17, 2006 at 06:16:36 Pacific
Reply:

BTW, The "Lots of Insignificant Silly Parentheses" joke is amusing but too many people actually believe (among other Lisp myths) that there's some truth in it. In fact the parentheses help to make the all-important structure of the program stand out more clearly and no-one would write Lisp programs in an editor that didn't take advantage of them.

http://paste.lisp.org/display/16899


0

Response Number 22
Name: geohoffman49431
Date: February 17, 2006 at 09:25:07 Pacific
Reply:

;) The acronym was something I saw online and thought was kinda funny, of couse lisp stands for list processor. I sort of like eLisp - it has an intuitive structure. I have heard Lisp is used in the field of artificial intelligence which is something I am interested in. Maybe I will look into it more. I dont run linux or use emacs so it would be kind of hard for me to learn eLisp, but I am guessing Lisp is similar in structure and useage.


0

Response Number 23
Name: Wolfbone
Date: February 17, 2006 at 12:26:19 Pacific
Reply:

Well if you do decide to look into this stuff some more, there're a lot of very good online resources (including helpful human ones) available via http, nntp and IRC.


0

Response Number 24
Name: dtech10
Date: February 18, 2006 at 15:17:14 Pacific
Reply:

Hi Geo
Something like this will convert decimal numbers to base 16.
I put it in Basic as thats a language most people know.
-------------
Str$="0123456789ABCDEF"
n$=""
Input "Number",N
Input "Base",B
While N>0 and B>1
Rem fpart=fractional part
P=int(fpart(N/B)*B)
N$=Mid$(Str$,P+1,1)+N$
N=Int(N/B)
EndWh
Print N$


0

Response Number 25
Name: jboy
Date: February 18, 2006 at 23:25:03 Pacific
Reply:

"G=16, H=17, I=18 ....."

Hi-larious (as noted, and personal 'charm' notwithstanding)


Science is built up with facts, as a house is with stones. But a collection of facts is not more a science than a heap of stones is a home


0

Response Number 26
Name: geohoffman49431
Date: February 20, 2006 at 01:37:00 Pacific
Reply:

meh, charm is overated ;) - You can get by on mental competence. Sides - us geeks don't get out much - I am pretty charming to my pocket calculator and my female robot I am building for companionship =).

On a side note it's 4:32 am and I am convinced that linear algebra is the devil. I shoulda taken multivariable calculus.


0

Response Number 27
Name: Wolfbone
Date: February 20, 2006 at 02:57:23 Pacific
Reply:

"meh, charm is overated ;) - You can get by on mental competence."

And for those 'programmers' who both lack charm and are somewhat limited in their ability to grasp simple ideas about ths representation of number, a cute face and a coat of fur can be very useful:

http://www.pri.kyoto-u.ac.jp/ai/video/video_library/Ai-Dot%20count%20040818.wmv

BTW, Linear algebra is more like God than the Devil, since it appears just about everywhere in maths, including analysis.


0

Response Number 28
Name: geohoffman49431
Date: February 20, 2006 at 07:17:40 Pacific
Reply:

lmao - that video rocks. If the monkey can do that maybe I can pass my linear algebra midterm.

I took the class because of its uses in graphics and geometry. It is not really that bad (if you don't wait three weeks to open the book). It just seems evil at 4 in the morning.


0

Response Number 29
Name: Mechanix2Go
Date: February 20, 2006 at 15:02:17 Pacific
Reply:

Hi dtech10,

It got stuck at on the first line and said:

expected : statement


If at first you don't succeed, you're about average.

M2


0

Response Number 30
Name: dtech10
Date: February 21, 2006 at 11:51:24 Pacific
Reply:

Hi mechanic
It it's the Str$="0123.." then change it to some other variable name, as most basic's have a function called Str$() to change a number into a string form.
My fault for calling it Str$ to signfy a string variable.


0

Response Number 31
Name: dtech10
Date: February 21, 2006 at 11:58:30 Pacific
Reply:

Hi mechanic
Also fpart() may not exist in you Basic, but
n=int((n/b-int(n/b)*b) will produce the same result.



0

Sponsored Link
Ads by Google
Reply to Message Icon

GetMessage function Batchfile prefix multiple...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: function to convert between bases

to convert uppercase to lowercase www.computing.net/answers/programming/to-convert-uppercase-to-lowercase/1831.html

how to convert chars to int www.computing.net/answers/programming/how-to-convert-chars-to-int/11828.html

How to convert Ascii to binary www.computing.net/answers/programming/how-to-convert-ascii-to-binary/829.html