Int/String conversion in C

In this forum members can discuss topics about specific programming languages.
Post Reply
Evans_Gambit
Posts: 1
Joined: Sun Aug 07, 2011 6:59 pm

Int/String conversion in C

Post by Evans_Gambit »

I'm using Xcode 3.1.3 and programming in C. What I'm not sure how to do is convert strings into integers and integers into strings. I need this to complete problem 4. I've looked online, and seen script that I (thought I) understood, but can't seem to get it to work myself.
thundre
Posts: 356
Joined: Sun Mar 27, 2011 10:01 am

Re: Int/String conversion in C

Post by thundre »

Evans_Gambit wrote:I'm using Xcode 3.1.3 and programming in C. What I'm not sure how to do is convert strings into integers and integers into strings. I need this to complete problem 4. I've looked online, and seen script that I (thought I) understood, but can't seem to get it to work myself.
For string to integer, use atoi and its sisters atol, atoll: http://en.wikipedia.org/wiki/Atoi

For integer to string, use sprintf.
Image
suitti
Posts: 12
Joined: Fri Jul 08, 2011 8:13 pm

Re: Int/String conversion in C

Post by suitti »

Sometimes you need to do things like reverse digits in a number. For this you do not necessarily have to convert to a string. You can use the modulus operator to pick digits off of the least significant end of a number:

a = x % 10; /* a gets the low digit */
x /= 10; /* x gets 'shifted' one decimal digit to the right */

So a loop like this:

int a;
int x;
a = 0;
while (x > 0) {
a *= 10;
a += x % 10;
x /= 10;
}

moves the number x into the variable a, reversing the digits. (It also destroys x, so if you still need it, you need to make a copy.) Such a loop is probably much faster at reversing digits than doing a sprintf(), reversing the characters in the string, then doing an atoi(). It also doesn't require a string buffer. One thing to watch is that if the original number has a zero in the least significant digit, it sort of disappears when it becomes the most significant digit on the other end.

In the really old days, when the target machine was an "8 bit" 8080, a machine with no hardware divide (or multiply), sprintf() and atoi() were optimized to not use real multiply or divide. They were quite fast at this compared to the above loop. But these days, CPUs have hardware multiply and divide, and they're really fast.
brainiac1530
Posts: 16
Joined: Sun Mar 02, 2014 2:32 pm

Re: Int/String conversion in C

Post by brainiac1530 »

Check out http://www.cplusplus.com/reference/cstdlib/

Keep in mind in a C implementation this will be called <stdlib.h>, I think.
Post Reply