Guys I need to write a program that will convert FROM and TO any bases ranging from 2 to 10.oh bases meaning binary, base 3 numbers, octal etc(up to 10)
The program should prompt for the base “converted to” and the base “converted from”.
Can somebody tell me how I need to go about this and what aspects of C maybe helpful. I will do the actual coding and report any problems. Thanks
base conversion in C
Started by jack1234, Nov 03 2007 03:01 AM
3 replies to this topic
#1
Posted 03 November 2007 - 03:01 AM
|
|
|
#2
Posted 03 November 2007 - 05:40 AM
You need to read about how to convert one base to another. It's relative simple, and not really hard. You can use integers for representation with relative small numbers, but if it's bigger numbers, you'll need strings for the representation.
I just made a function, only using integers for representation. It's able to convert from decimal to Base-(2...9) Base-11 and up is not supported, because it's requires special signs, and not only digits. Here you're...
I just made a function, only using integers for representation. It's able to convert from decimal to Base-(2...9) Base-11 and up is not supported, because it's requires special signs, and not only digits. Here you're...
// The function
// First parameter: The base to convert to
// Second parameter: The number to be converted
int GetBase(int iBase, int iNumber)
{
if(iBase < 2 || iBase > 10)
return 0;
int iResult = iNumber % iBase;
int iMultiplier = 10;
while((iNumber /= iBase) > 0)
{
iResult = (iNumber % iBase) * iMultiplier + iResult;
iMultiplier *= 10;
}
return iResult;
}
// A test, to see how it works
int i;
for(i = 2; i < 10; i++)
printf("123 in Base-%d: %d\n", i, GetBase(i, 123));
// Sample run 123 in Base-2: 1111011 123 in Base-3: 11120 123 in Base-4: 1323 123 in Base-5: 443 123 in Base-6: 323 123 in Base-7: 234 123 in Base-8: 173 123 in Base-9: 146
#3
Posted 05 November 2007 - 03:40 AM
Thanks! I got a simpler way but I am stuck at how can I implement a code that tests the amount of integers enterd and multiply that integer/s by powers starting at 0. eg 1234 in base 8 would be (1x8*3)+(2x8*2)+(3x8*1)+(4x8*0) (converted to base 10)
I am having problems on how to get the program to multiply by the right amount of integers and using the right amount of powers.
I am having problems on how to get the program to multiply by the right amount of integers and using the right amount of powers.
#4
Posted 05 November 2007 - 09:19 AM
Log base 10 will give you the number of digits - 1. So digits = ln(number)/ln(10) + 1.


Sign In
Create Account

Back to top









