Saturday, December 17, 2011

How do I convert numbers from base 10 to any base?

I am write a subroutine that given a number N in base 10 and a base value Base between 2 and 10 (inclusive), returns the representation of the decimal value N in the desired Base.I know how to convert bases by pen, but it is hard to write this thing....|||log(number)/log(base)





Example:


log(8)/log(2) = 3 = log[base2] 8





Edit: Oops, nevermind, I read log somewhere, it must have been in my head.





Converting to base 10 is easy.





In general, instead of using a specific language since I don't know what you're using:


Convert the number to a string if necessary.


Loop through the length of the number/number string.


Convert each position to an integer.


Raise the base to the power of the length of the string - the position.


Add that number to the total.





From decimal to another base:


NOW you use log to find the highest power of the base you're converting to.


int(log(number)/log(base)) = highest power if the base you're converting to.


I'll let you take it from there. I just wanted to get to my logs!|||what program language r u using?





first u would want to define how each base handle each number, like binary base 2, 21 = 10101, so u get need to get the math part down to what happens for each base (i think divide the number by the base and put a spot there like dividing 21 by 2(the base number) = 10.5 since the number is not a whole number put a 1 then divide 10 by 2 again and that is evenly goes though so that is a 0, work form right to left until u cant divide anymore so 21 = 10101, i.e. converting decimal to binary. for a different base just divide by that base i.e hex base 16. then have 2 number inputs or generators one for the base and one for the number and it does that formal depending on the base number. |||Checkout solution in javascript at site listed in source.



No comments:

Post a Comment