October 29, 2004

About converting from ASCII to integer, integer to ASCII, and casting ints as chars and chars as ints

These topics came up in my CPSC 220 class today.
The course deals with C++ and we've worked with the string class.

Converting from ASCII to integer and from integer to ASCII
need to work with C strings rather than C++ strings.
The conversion is easy, though.
For this discussion suppose we have the declarations
#include
string si, sj;
int i, j;
si = "1234"; sj = "-3458";

We can convert these strings to integers by using the function atoi as follows.

i = atoi(si.c_str()); j = atoi(sj.c_str());

We need to use the method c_str() of the string class, because atoi expects an argument of type char *.

To convert a decimal integer to a string, it's easy if you
use sprintf as follows
i = 123;
sprintf(si.c_str(),"%d",i);

The integer i is stored as a decimal (%d) integer and stored
in the string si.

For more info on these take a look at
http://www.iota-six.co.uk/c/g3_atoi_itoa_sprintf_sscanf.asp

Converting characters to their ASCII equivalent can be done
with an explicit cast as in
int i;
string si = "1234";
i = int(si[3]);

In the case above i gets the value 52 which is the ASCII value
for '4'.

Converting the other way is quite natural as in
si[3] = char (i);

In this case s[3] has the same value as it started with.
That is,

si[3] = char ( int (si[3]) );

Posted by ernie at October 29, 2004 05:30 PM | TrackBack
Send a comment
Comments