C Board  

Go Back   C Board > General Programming Boards > C++ Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 01-17-2005, 05:02 PM   #1
Registered User
 
cdonlan's Avatar
 
Join Date: Sep 2004
Posts: 49
Base converter library

Im trying to convert a number to a different base. Does anyone know what library has the converter in it.

Thanks

Last edited by cdonlan; 01-17-2005 at 05:07 PM.
cdonlan is offline   Reply With Quote
Old 01-17-2005, 06:05 PM   #2
UT2004 Addict
 
Kleid-0's Avatar
 
Join Date: Dec 2004
Posts: 645
It took a long time! But I got it!! I've got the golden ticket! It took some testing, but now it's bake-ready! It's for C, but of course you could compile this in C++. And no negative comments plz, I took awhile peicing this together.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

#define  MAXREAL  1e40

int   ba,bd;
char  x[40],y[40];
float r;

enum bool {
 TRUE, FALSE
};

char *strrev(const char *s) {
 int i=0, len=strlen(s);

 char *str = NULL;
 if ((str=malloc(strlen(s)+1)) == NULL) {/*cannot allocate memory */
  return NULL;
 }

 while(len)
  str[i++]=s[--len];
 str[i] = '\0';
 return (str);
}

// Convert a number from base b to base 10. The function returns
// FALSE if b not in [2..36] or if string x contains invalid
// characters in base b or if result y is too big.
enum bool DecodeBase(char *x,int b, float *y) {
 int lgth,i,j;
 float mult; char *ch;
 if (b<2 || b>36) {
  printf(" Base must be between 2 and 36 !\n");
  return FALSE;
 }
 *y=0; mult=1.0;
 lgth=strlen(x);
 for (i=0; i<lgth; i++) {
  ch=&x[lgth-i-1];
  if (!isalnum(ch[0])) {
  printf(" Error in input number.\n");
  return FALSE;
  }
  if (*ch<='9')
  j=toupper(*ch)-'0';
  else
   j=toupper(*ch)-'A'+10;
  if (j>=b) return FALSE;
  *y+=mult*j;
  if (mult>MAXREAL/b) return FALSE;
  mult=mult*b;
 }
 return TRUE;
}

//Convert a number from base 10 to base b. The function returns
//FALSE if b not in [2..36] or if string x contains invalid
//characters in base 10 or if number x is too big.
enum bool CodeBase(float x,int b, char *y) {
 int n; char ch[2];
 if (b<2 || b>36) {
  printf(" Base must be between 2 and 36 !\n");
  return FALSE;
 }
 strcpy(y, "");
 while (x>0) {
  n=(int) floor(x - b * (int)(x/b));
  if (n<10) {
   //y=Chr(Ord("0")+n)+y;
   sprintf(ch,"%d",n);
  strcat(y,ch);
  }
  else {
   //y=Chr(Ord("A")+n-10) +y;
   switch(n) {
   case 10: strcat(y,"A"); break;
   case 11: strcat(y,"B"); break;
   case 12: strcat(y,"C"); break;
   case 13: strcat(y,"D"); break;
   case 14: strcat(y,"E"); break;
   case 15: strcat(y,"F"); break;
   case 16: strcat(y,"G"); break;
   case 17: strcat(y,"H"); break;
   case 18: strcat(y,"I"); break;
   case 19: strcat(y,"J"); break;
   case 20: strcat(y,"K"); break;
   case 21: strcat(y,"L"); break;
   case 22: strcat(y,"M"); break;
   case 23: strcat(y,"N"); break;
   case 24: strcat(y,"O"); break;
   case 25: strcat(y,"P"); break;
   case 26: strcat(y,"Q"); break;
   case 27: strcat(y,"R"); break;
   case 28: strcat(y,"S"); break;
   case 29: strcat(y,"T"); break;
   case 30: strcat(y,"U"); break;
   case 31: strcat(y,"V"); break;
   case 32: strcat(y,"W"); break;
   case 33: strcat(y,"X"); break;
   case 34: strcat(y,"Y"); break;
   case 35: strcat(y,"Z");
  }
  }
  x=(float) (int)(x/b);
 }
 y=strrev(y); //string inversion
 return TRUE;
}

int main(void)  {

 int theBaseIWant = 2;
 int theNumber = 40;
 char Output[255];

 // From base 10 -> 2
 if(CodeBase(theNumber, theBaseIWant, Output) == TRUE) {
  puts(Output);
 }
 else {
  puts("WWWHHYY!!");
  return 0;
 }

 // From Base 16(Hex) --> Base 2(Binary)
 float decimal;
 char Input[] = "00FF";
 if(DecodeBase(Input, 16, &decimal) == FALSE) {
  puts("WWWHHYY!!");
  return 0;
 }

 if(CodeBase(decimal, 2, Output) == FALSE) {
  puts("WWWHHYY!!");
  return 0;
 }

 printf("Our decimal: %.2f\n", decimal);

 /* Tested the strrev() function
 char *myWord = "Hello World";
 char WordBackwards[strlen(myWord)+1];

 if(strrev(myWord) != NULL) {
  strcpy(WordBackwards, strrev(myWord));
  puts(WordBackwards);
 }
 else {
  puts("AAHH!!");
 }*/

 /* Original source
 printf("\n BASE CONVERSION\n\n");
 printf(" Start  Base (2 to 36): "); scanf("%d",&bd);
 printf(" Arival Base (2 to 36): "); scanf("%d",&ba);
 strcpy(x,"1");
 while (strcmp(x,"0")!=0) {
  printf("\n Enter number in start base: "); scanf("%s",x);
  if (strcmp(x,"0")!=0) {
   if (DecodeBase(x,bd,&r)) {
   if (CodeBase(r,ba,y))
    printf(" In base %d:  %s\n",ba,y);
   else
    printf(" Error in coding number.\n");
   }
   else
   printf(" Error in decoding number.\n");
  }
 }
 printf("\n\n");*/

 return 0;
}
Kleid-0 is offline   Reply With Quote
Old 01-17-2005, 06:56 PM   #3
Registered User
 
cdonlan's Avatar
 
Join Date: Sep 2004
Posts: 49
If I only need bases 3 ,5,7, and 9. And the largest the number could go up to is 1,000,000 I could cut out a lot of that stuff In the 10 to b-base function.
cdonlan is offline   Reply With Quote
Old 01-17-2005, 07:00 PM   #4
UT2004 Addict
 
Kleid-0's Avatar
 
Join Date: Dec 2004
Posts: 645
Well you probably could, it was made to work with base-2 through base-30 I believe.
Kleid-0 is offline   Reply With Quote
Old 01-17-2005, 07:12 PM   #5
Registered User
 
cdonlan's Avatar
 
Join Date: Sep 2004
Posts: 49
For some reason it does not like the strrev function. I included all the header files.
cdonlan is offline   Reply With Quote
Old 01-17-2005, 07:26 PM   #6
Slave
 
MadCow257's Avatar
 
Join Date: Jan 2005
Posts: 735
then use my code
it converts base 10 to any base (2-36)
I just threw it together, but it works fine I think.
Code:
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
	string output;
	int input, base, counter=0;
	cout << "Please input the number to be converted: ";
	cin >> input;
	cout << "Please input the base to convert to: ";
	cin >> base;
	while (input != 0)
	{
		switch (input % base)
		{
		case 0:
			output += '0';
			break;
		case 1:
			output += '1';
			break;
		case 2:
			output += '2';
			break;
		case 3:
			output += '3';
			break;
		case 4:
			output += '4';
			break;
		case 5:
			output += '5';
			break;
		case 6:
			output += '6';
			break;
		case 7:
			output += '7';
			break;
		case 8:
			output += '8';
			break;
		case 9:
			output += '9';
			break;
		case 10:
			output += 'A';
			break;
		case 11:
			output += 'B';
			break;
		case 12:
			output += 'C';
			break;
		case 13:
			output += 'D';
			break;
		case 14:
			output += 'E';
			break;
		case 15:
			output += 'F';
			break;
		case 16:
			output += 'G';
			break;
		case 17:
			output += 'H';
			break;
		case 18:
			output += 'I';
			break;
		case 19:
			output += 'J';
			break;
		case 20:
			output += 'J';
			break;
		case 21:
			output += 'K';
			break;
		case 22:
			output += 'L';
			break;
		case 23:
			output += 'M';
			break;
		case 24:
			output += 'N';
			break;
		case 25:
			output += 'O';
			break;
		case 26:
			output += 'P';
			break;
		case 27:
			output += 'Q';
			break;
		case 28:
			output += 'R';
			break;
		case 29:
			output += 'S';
			break;
		case 30:
			output += 'T';
			break;
		case 31:
			output += 'U';
			break;
		case 32:
			output += 'V';
			break;
		case 33:
			output += 'W';
			break;
		case 34:
			output += 'X';
			break;
		case 35:
			output += 'Y';
			break;
		case 36:
			output += 'Z';
			break;
		}
		input = input/base;
		counter++;
	}
	cout << "The result of the conversion is ";
	while (counter > -1)
	{
		cout << output[counter];
		counter--;
	}
	cout << "\n";
	return 0;
}
MadCow257 is offline   Reply With Quote
Old 01-17-2005, 07:27 PM   #7
Registered User
 
cdonlan's Avatar
 
Join Date: Sep 2004
Posts: 49
Thanks a lot guys
cdonlan is offline   Reply With Quote
Old 01-17-2005, 07:47 PM   #8
UT2004 Addict
 
Kleid-0's Avatar
 
Join Date: Dec 2004
Posts: 645
Quote:
Originally Posted by cdonlan
For some reason it does not like the strrev function. I included all the header files.
What's the error code? It works fine for me. strrev() is also inside <windows.h>, so beware. You may want to rename strrev to strrev2 just so there aren't any conflicting methods. Good luck!

Nice function MadCow
Kleid-0 is offline   Reply With Quote
Old 01-17-2005, 08:12 PM   #9
C Programmer
 
Stack Overflow's Avatar
 
Join Date: Apr 2004
Posts: 477
Well,

Since this is the C++ section, and not C, strrev() would not be the first to choose from. strrev() is not within the C++ standard. Though, there is another function that is within the C++ standard library called reverse_copy().

Looking closer at Kleid-0's code, I see that he passes a character array that holds 255 characters to CodeBase(). Though when he handles it, he passes that function to strrev() which allocates memory to it. Just an observation.

Even though strrev() isn't standard, it could be done simply by using the XOR method:
Code:
char* strrev(char *str) {
	char *p1, *p2;

	if (!str || !*str)
		return str;

	for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
		*p1 ^= *p2;
		*p2 ^= *p1;
		*p1 ^= *p2;
	}

	return str;
}
All in all, I don't see a need to use a C-style function in C++.


- Stack Overflow
__________________
Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.
Stack Overflow is offline   Reply With Quote
Old 01-17-2005, 08:26 PM   #10
Handy Andy
 
andyhunter's Avatar
 
Join Date: Dec 2004
Posts: 540
Kleid-0, you need to take a break pal. Go get laid or drunk or both.
__________________
i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem
andyhunter is offline   Reply With Quote
Old 01-17-2005, 08:29 PM   #11
UT2004 Addict
 
Kleid-0's Avatar
 
Join Date: Dec 2004
Posts: 645
YOU JUST BACK OFF ANDY!!! lol, j/k . I deleted that post, I was releasing too much negative energy!
Kleid-0 is offline   Reply With Quote
Old 01-18-2005, 02:35 PM   #12
Hardware Engineer
 
Join Date: Sep 2001
Posts: 1,398
strtoul() will convert from any base (2-36) to a standard integer.

cout can display a number in octal, decimal, or hex, and with a little help from <bitset> you can display in binary.

There isn't a standard built-in function to convert from a standard integer to any base. But if you have a Microsoft compiler, itoa() will do exactly that.

Note that any conversion is normally done only during input or output. The above functions convert between an integer and a C-style-string representation of the number in another base.

All variables in the computer's memory are stored in binary. C++ changes it to decimal input/output by default. This means that you can enter one number in decimal, another in hex, add them together, and display the result in octal, without worrying about the fact that you mixing bases!

Here's an example program I wrote a couple of years ago:
Attached Files
File Type: cpp base.cpp (2.5 KB, 33 views)
DougDbug is offline   Reply With Quote
Old 05-14-2005, 03:28 AM   #13
Registered User
 
Join Date: Apr 2005
Posts: 53
Quote:
Originally Posted by MadCow257
then use my code
it converts base 10 to any base (2-36)
I just threw it together, but it works fine I think.
Code:
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
	string output;
	int input, base, counter=0;
	cout << "Please input the number to be converted: ";
	cin >> input;
	cout << "Please input the base to convert to: ";
	cin >> base;
	while (input != 0)
	{
		switch (input % base)
		{
		case 0:
			output += '0';
			break;
		case 1:
			output += '1';
			break;
		case 2:
			output += '2';
			break;
		case 3:
			output += '3';
			break;
		case 4:
			output += '4';
			break;
		case 5:
			output += '5';
			break;
		case 6:
			output += '6';
			break;
		case 7:
			output += '7';
			break;
		case 8:
			output += '8';
			break;
		case 9:
			output += '9';
			break;
		case 10:
			output += 'A';
			break;
		case 11:
			output += 'B';
			break;
		case 12:
			output += 'C';
			break;
		case 13:
			output += 'D';
			break;
		case 14:
			output += 'E';
			break;
		case 15:
			output += 'F';
			break;
		case 16:
			output += 'G';
			break;
		case 17:
			output += 'H';
			break;
		case 18:
			output += 'I';
			break;
		case 19:
			output += 'J';
			break;
		case 20:
			output += 'J';
			break;
		case 21:
			output += 'K';
			break;
		case 22:
			output += 'L';
			break;
		case 23:
			output += 'M';
			break;
		case 24:
			output += 'N';
			break;
		case 25:
			output += 'O';
			break;
		case 26:
			output += 'P';
			break;
		case 27:
			output += 'Q';
			break;
		case 28:
			output += 'R';
			break;
		case 29:
			output += 'S';
			break;
		case 30:
			output += 'T';
			break;
		case 31:
			output += 'U';
			break;
		case 32:
			output += 'V';
			break;
		case 33:
			output += 'W';
			break;
		case 34:
			output += 'X';
			break;
		case 35:
			output += 'Y';
			break;
		case 36:
			output += 'Z';
			break;
		}
		input = input/base;
		counter++;
	}
	cout << "The result of the conversion is ";
	while (counter > -1)
	{
		cout << output[counter];
		counter--;
	}
	cout << "\n";
	return 0;
}

I'm writing a similiar program that also accomplishes a conversion task, but I'm trying to rewrite this so that for a value it would print out all the conversions from base 2 up to base 30. I was wondering what would be the best way to translate it and print out all bases instead of a specific. Thanks.
cisokay is offline   Reply With Quote
Old 05-14-2005, 09:59 AM   #14
He's trying.
 
Join Date: Apr 2005
Location: Missouri, US
Posts: 70
I made something like this (Decimal to BASE) a couple weeks ago...I'm not so good, but I think this does pretty much what it's supposed to.

It'll go up to base...36, I think. It doesn't have any case statements!
Attached Files
File Type: cpp DecToX.cpp (1.3 KB, 33 views)
Nazca is offline   Reply With Quote
Old 05-14-2005, 11:43 AM   #15
Registered User
 
Join Date: Apr 2005
Posts: 53
I just took a look at the file, it actually does have case statments. I'm just trying to get a simplified version of the code but being able to take argv[1] and conver it from base 2 up to base 30. Bascially not having to specify the cases. I tried to modifed the other verison that I put up, but I get some weird errors. I'm not sure how they looped through it to actually get the values. Thank you.
cisokay is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Code review Elysia C++ Programming 71 05-13-2008 09:42 PM
Base Converter Part 2 encyclopedia23 C Programming 2 12-30-2006 02:42 PM
Base Converter encyclopedia23 C Programming 3 12-29-2006 08:55 AM
Base10 to Base n converter P4r4digm C++ Programming 1 10-04-2006 09:34 PM
Help With Libary Data Base. Dangerous Dave C Programming 5 04-23-2002 06:21 PM


All times are GMT -6. The time now is 05:32 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22