Thread: int to char

  1. #1
    Burning in Hell! Luigi's Avatar
    Join Date
    Nov 2002
    Posts
    117

    int to char

    I wanna make an function that converts int to char..

    but i just cant figure out how to go through each number contained in an int..

    like int a = 123;

    use a pointer (maybe?) to point at each number at a time..

    1
    2
    3
    ...

    I tried this:

    Code:
    void itoa(int i, char b[])
    {
          int a = length(b);
          for (int j = 0; j < a ; j++)
          {
    	  b[j] = i[j];	//???
          }
    }
    But this doesnt work.. cant use array on int..
    what should I do?

    thx
    Luigi

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    There's some conversion examples here. Maybe they will help you.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    ~

    Just use the standard itoa. it's in <cstdlib> I think?
    "He who makes a beast of himself, gets rid of the pain of being a man." Dr. Johnson

  4. #4
    Registered User axon's Avatar
    Join Date
    Feb 2003
    Posts
    2,572
    maybe try typecasting?

    Code:
    (char)i[j]
    axon

    some entropy with that sink? entropysink.com

    there are two cardinal sins from which all others spring: Impatience and Laziness. - franz kafka

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231

    Re: ~

    Originally posted by rmullen3
    Just use the standard itoa. it's in <cstdlib> I think?
    itoa() is not standard. Maybe you've confused it with atoi().

    >>maybe try typecasting?
    I don't think that will do what the OP wants.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  6. #6
    Burning in Hell! Luigi's Avatar
    Join Date
    Nov 2002
    Posts
    117
    Is there a way to make it using only <iostream>?

    Luigi

  7. #7
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    ~

    Oh, my mistake. Why is itoa not in the standard and atoi is?
    "He who makes a beast of himself, gets rid of the pain of being a man." Dr. Johnson

  8. #8
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    ~

    Luigi, here's the xtoa function, maybe it will help you:

    Code:
    static void __cdecl xtoa (
            unsigned long val,
            char *buf,
            unsigned radix,
            int is_neg
            )
    {
            char *p;                /* pointer to traverse string */
            char *firstdig;         /* pointer to first digit */
            char temp;              /* temp char */
            unsigned digval;        /* value of digit */
    
            p = buf;
    
            if (is_neg) {
                /* negative, so output '-' and negate */
                *p++ = '-';
                val = (unsigned long)(-(long)val);
            }
    
            firstdig = p;           /* save pointer to first digit */
    
            do {
                digval = (unsigned) (val % radix);
                val /= radix;       /* get next digit */
    
                /* convert to ascii and store */
                if (digval > 9)
                    *p++ = (char) (digval - 10 + 'a');  /* a letter */
                else
                    *p++ = (char) (digval + '0');       /* a digit */
            } while (val > 0);
    
            /* We now have the digit of the number in the buffer, but in reverse
               order.  Thus we reverse them now. */
    
            *p-- = '\0';            /* terminate string; p points to last digit */
    
            do {
                temp = *p;
                *p = *firstdig;
                *firstdig = temp;   /* swap *p and *firstdig */
                --p;
                ++firstdig;         /* advance to next two digits */
            } while (firstdig < p); /* repeat until halfway */
    }
    and the itoa function that uses xtoa:

    Code:
    char * __cdecl _itoa (
            int val,
            char *buf,
            int radix
            )
    {
            if (radix == 10 && val < 0)
                xtoa((unsigned long)val, buf, radix, 1);
            else
                xtoa((unsigned long)(unsigned int)val, buf, radix, 0);
            return buf;
    }
    "He who makes a beast of himself, gets rid of the pain of being a man." Dr. Johnson

  9. #9
    Geek. Cobras2's Avatar
    Join Date
    Mar 2002
    Location
    near Westlock, and hour north of Edmonton, Alberta, Canada
    Posts
    113
    It would be easiest to use the standard functions to do the conversion - just use sprintf;
    Code:
    sprintf(b, "%i", i);
    if I remember correctly.. I believe it's in the <cstring> header


    I wanna make an function that converts int to char..
    You do mean char* right? as in a string? because converting an int (which has a minimum range of -32,767 to 32,767) will take up to 6 characters to display (unless of course it(the int) is bigger than that, which it probably will be, since 16 bits is the *minimum* required by the standard)

    but i just cant figure out how to go through each number contained in an int..

    like int a = 123;

    use a pointer (maybe?) to point at each number at a time..

    1
    2
    3
    ...
    remember, the int is not a string of chars. It's binary; i.e. it looks like this if it's 123;
    01111011
    altho it will probably also have a bunch of zeros in front of it (likely either 8 or 24), wheras the ASCII characters 1 2 and 3 look like;
    00011111 00100000 and 00100001
    each character is one byte (8 bits).

    But if you really want to do it yourself.. I would suggest starting with the 1's place and moving up to the top, remembering each digit as you go, and then create a string and put the char values into it.

    [edit]
    lol.. by the time I posted this there was already a bunch of other replies
    actually if you follow Hammer's link above you will also end up at a description of sprintf
    [/edit]
    Last edited by Cobras2; 03-03-2003 at 06:58 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

  10. #10
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    It would be easiest to use the standard functions to do the conversion - just use sprintf;
    Stringstreams are quite superior, and provide the same functionality.
    Code:
    int num = 200;
    std::string strnum;
    
    std::stringstream convert;
    convert << num;
    convert >> strnum;
    Have a look in the FAQ

  11. #11
    Geek. Cobras2's Avatar
    Join Date
    Mar 2002
    Location
    near Westlock, and hour north of Edmonton, Alberta, Canada
    Posts
    113

    Oh yeah.. stringstream..

    totally forgot that (stringstream) one haven't done too much with it myself so the only one I've actually used is sprintf.
    Anyway, I was just gonna post, I was bored, and the idea of writing a itoa sounded kinda fun, so I did...


    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    void myitoa(int, char*, int);
    int xpower(int, int);
    
    int main()
    {
    	char* bob = new char[40]; //note the lack of proper checking because this is just a quick test..
    	int i;
    	for(i=-32767;i<=32767;i++)
    	{
    		myitoa(i, bob, 40);
    		cout << bob << " ";
    		if(!(i%10))
    		{
    			cout << "\n";
    		}
    	}
    	return 0;
    }
    
    int xpower(int i, int pwr)
    {
    	int loop, ret=i;
    	if(!pwr) return 1;
    	if(pwr == 1) return i;
    	for(loop=1;loop<pwr;loop++)
    	{
    		ret *= i;
    	}
    	return ret;
    }
    
    void myitoa(int i, char* b, int sizeb)
    {
    	if(!b || !sizeb) return;
    	int j=0, r=i;
    	int szint = sizeof(int)*8;
    	char* buf=0;
    	char* s=0;
    	try {
    		buf = new char[szint+1];
    	} catch(...) {
    		cout << "error allocating memory\n";
    		buf=0;
    	}
    	if(buf)
    	{
    		s=buf+1;
    		int c;
    		for(j=0;j<szint;j++) *(buf+j) = '0';
    		*(buf+szint+1) = '\0';
    		if(i < 0)
    		{
    			r = (-(i));
    		}
    		j=10;
    		for(c=0;c<szint-1;c++)
    		{
    			*(s+szint-c-1) = (char)('0' + (r%j)/xpower(10, c));
    			r -= (r%j);
    			j*=10;
    		}
    		s = buf+1; c=0;
    		while(*s == '0' && c++ < szint-1) s++;
    		strncpy(b, s, sizeb);
    		if(i<0)
    		{
    			for(j=sizeb;j>0;j--) *(b+j) = *(b+j-1);
    			*b = '-';
    		}
    		if(c < sizeb) *(b+c) = '\0';
    	}
    	*(b+sizeb) = '\0';
    }
    goes to show what someone can accomplish when they're bored.. that was pretty fun, actually.. thx for the challenge Luigi
    plus from the looks of it it should even work whether the int is 16 or 32 bit.. tell me what you think?
    man I wish I could get my bitmap loading function working as good as this turned out
    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

  12. #12
    Burning in Hell! Luigi's Avatar
    Join Date
    Nov 2002
    Posts
    117
    well I just tried your code... works just fine
    eventho I changed the main to take a number using cin..

    but didnt go through the code..

    cause at first the challenge was for me..
    so looking to your code would be like cheating..

    but Ill use it as a reference.. will also compare mine to yours when im done..

    Luigi

  13. #13
    Geek. Cobras2's Avatar
    Join Date
    Mar 2002
    Location
    near Westlock, and hour north of Edmonton, Alberta, Canada
    Posts
    113
    hehe.. I was going to mention, that if the idea was for you to write one yourself, you might not want to look at mine

  14. #14
    Burning in Hell! Luigi's Avatar
    Join Date
    Nov 2002
    Posts
    117
    cobra could you add some comments to your myitoa() function?

    I still consider myself beginner but soon to be intermediate..

    would help me a lot

    u can either post it here email it to me..
    [email protected]

    thx in advance

    Luigi

  15. #15
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    At a quick glance, I'd say this is a buffer overflow problem:
    >>*(buf+szint+1) = '\0';
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

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, 04: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