Jump to content

base conversion in C

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
jack1234

jack1234

    Newbie

  • Members
  • Pip
  • 4 posts
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

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
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...
// 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
jack1234

jack1234

    Newbie

  • Members
  • Pip
  • 4 posts
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.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Log base 10 will give you the number of digits - 1. So digits = ln(number)/ln(10) + 1.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog