int to char

This is a discussion on int to char within the C++ Programming forums, part of the General Programming Boards category; firstly, I have no idea now that I look at ti again, how I managed to get away with that. ...

  1. #16
    Geek. Cobras2's Avatar
    Join Date
    Mar 2002
    Location
    near Westlock, and hour north of Edmonton, Alberta, Canada
    Posts
    113
    firstly, I have no idea now that I look at ti again, how I managed to get away with that.
    I think I'll post a couple notes on what I noticed I did wrong, and then post a better version, with comments included (if you also want it in an email just ask, it might be a bit harder to read on here)
    ok here goes for the errors I made yesterday(at least the ones I noticed):
    first of all, adding the char at the beggining of buf was pointess since I only added a '-' to the beggining of b, never buf.
    secondly, I was using j to keep track of which place I was in.. but how did that work?? j is only an int, so it's surprising i didn't get errors - i suppose I should have made sure the function could handle even large ints properly.
    thirdly, I was putting a null terminator on the char *after* the end of b
    and another thing - after using the first char of buf for something else, i never made buf long enough, so it was actually only using sizeint-1 chars, which means it couldn't handle a large int anyway.
    Well, I don't know how that slipped past me, but here's a hopefully better solution:
    Code:
    /i is the int we want to convert, b is the string we'll put it into,
    //and sizeb is the length of string b
    //(actually since the string starts at 0, sizeb should be
    //the last element of b
    void myitoa(int i, char* b, int sizeb)
    {
      //if the string doesn't point to anything,
      //or if it's 0 length, return
    	if(!b || !sizeb) return;
    	//j is for the loops, r is the temp variable for getting the value out of i
    	int j=0, r=i;
    	//this tells us how many bits an int has (assuming a byte has 8 bits.. I *think* this is safe? I may be wrong tho)
    	int szint = sizeof(int)*8;
    	//buf is the string we'll use to work on, s will point to the current spot we're working on
    	char* buf=0;
    	char* s=0;
    	//allocate enough memory to handle the size of an int.. + 1 for the /0 at the end
    	try {
    		buf = new char[szint+1];
    	} catch(...) {
    		cout << "error allocating memory\n";
    		buf=0;
    	}
    	//this way if there was an error we won't go trying to write an invalid pointer
    	if(buf)
    	{
    		int c;
    		//initialize the string to be all '0's and slap a null terminator on it
    		for(j=0;j<szint;j++) *(buf+j) = '0';
    		*(buf+szint) = '\0';
    		//now if i is a negative number, reverse the sign on r
    		//and then just treat it as a normal positive number
    		//this was a hack cause I totally forgot to include support for
    		//negative numbers untill like 2 minutes before I was going to post the code ;)
    		if(i < 0)
    		{
    			r = (-(i));
    		}
    		//have no idea how the old way wokred at all..
    		//s starts at the end of buf and works backwards
    		s=buf+szint;
    		//until it hits the beggining
    		while(s >= buf)
    		{
    		  //make the char at s's current address = '0' + whatever is in the current place;
    		  //if r == 756 for instance, r%756 == 6; and '0' + 6 = '6'
    		  *s = (char)('0' + r%10);
    		  //then switch to the next place by dividing by ten
    		  r /= 10;
    		  //and switch to the next(or rather previous ^.^) char by decreasing s
    		  s--;
    		}
    		s=buf; c=0;
    		//remove the leading 0s since they look stupid -
    		//what I'm actually doing is just having s point to the first character that is not 0 -
    		//unless it's the only one in the string, in which case it will just point to the last one
    		while(*s == '0' && c++ < szint) s++;
    		//now copy it into the string we were passed, making sure not to write too far
    		strncpy(b, s, sizeb);
    		//and, if i was a negative number, shift the characters in b over to the right and make the first one a '-'
    		//(might be a more efficient way of doing this but like I said, I just hacked it in two minutes before posting :P
    		//and it actually works too hehe)
    		if(i<0)
    		{
    			for(j=sizeb;j>0;j--) *(b+j) = *(b+j-1);
    			*b = '-';
    		}
    		//now if the b string is long enough to hold our whole string, cap it at the end of our string,
    		//so we won't have gibberish after the number
    		if(c < sizeb) *(b+c) = '\0';
    	}
    	//and also be sure to cap the end of b once we're done with it, even if it doesn't hold our whole string.
    	*(b+sizeb) = '\0';
    }
    edit {
    re:Hammer
    quite correct, it was, which is part of the reason why I'm not sure how I got away with it ^.^
    }
    Last edited by Cobras2; 03-04-2003 at 04:30 PM.
    James G. Flewelling
    Rgistered Linux User #327359
    Athabasca University Student (BSc. CIS)

    http://catb.org/~esr/faqs/smart-questions.html
    http://catb.org/jargon/

    http://www.ebb.org/ungeek
    ---GEEK CODE---
    Version: 3.12
    GCS/IT/M d- s+:++ a-->->>+>++>+++>? C++++>$ UL++>++++$ P++>++++ L++>++++$
    E W++ N o? K? w++(--)>--- O? M? V? PS--(---) PE Y+ PGP? t 5? !X R(*)>++
    tv-->! b++(+++)>++++ DI? D+++(---)>++++$ G e*>++$ h++>*$ r!>+++ y?
    ----/GEEK CODE----
    upd: 2005-02-11

  2. #17
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    edit {
    re:Hammer
    quite correct, it was, which is part of the reason why I'm not sure how I got away with it ^.^
    }
    ... you didn't, in a way: it was spotted by another programmer (ie me). The computer running the program will show this type of problem in undefined ways, maybe not even at all. That's the problem with overflows, you never know when they're going to crash your program.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #18
    Geek. Cobras2's Avatar
    Join Date
    Mar 2002
    Location
    near Westlock, and hour north of Edmonton, Alberta, Canada
    Posts
    113
    quite true
    in fact if I had tested the code a little better I probably would have seen it sooner - which just goes to show that even when coding just a quick little bit of code you should make sure to check it out properly
    James G. Flewelling
    Rgistered Linux User #327359
    Athabasca University Student (BSc. CIS)

    http://catb.org/~esr/faqs/smart-questions.html
    http://catb.org/jargon/

    http://www.ebb.org/ungeek
    ---GEEK CODE---
    Version: 3.12
    GCS/IT/M d- s+:++ a-->->>+>++>+++>? C++++>$ UL++>++++$ P++>++++ L++>++++$
    E W++ N o? K? w++(--)>--- O? M? V? PS--(---) PE Y+ PGP? t 5? !X R(*)>++
    tv-->! b++(+++)>++++ DI? D+++(---)>++++$ G e*>++$ h++>*$ r!>+++ y?
    ----/GEEK CODE----
    upd: 2005-02-11

  4. #19
    Burning in Hell! Luigi's Avatar
    Join Date
    Nov 2002
    Posts
    117
    finally made one myself:

    very similar to yours cobra..
    (I know.. didnt make comments either..)

    Code:
    char* itoa(int integer, char* abc)
    {
          int t_int = integer;
          char* buffer = abc;
          while(t_int)	  
          {
    	  *buffer++;
    	  t_int/= 10;
          }
          t_int = integer;
          if(integer<0)
          {
    	  *buffer++;
    	   t_int = (-(integer));
          }
    	  *buffer = '\0';	  
    	  do {
    	        *--buffer = ((char)('0'+t_int%10));
    	        t_int/= 10;
    	  } while(t_int);
    	   if(integer<0) *--buffer = '-';
          return buffer;
    }
    Luigi

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  3. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  4. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 03:24 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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