On Tue, 23 Sep 2003, Sona wrote:
Hi,
I have a char* that holds an ascii character in its first element (at
least I think that's what it holds because when I print it, it prints
weird characters). I need to convert this into an integer and so I
thought the following might work:
Whoa! There is a few problems here. I think you need to take a moment and
understand the terminology you are using. Your reasoning as to why the
first character that your pointer to char points at is ASCII makes no
sense. ASCII is a system for representing a character set. It just states
that certain binary values will be treated as certain characters. For
example, the binary value 48 or 0x30 will be the character '0'. The fact
that printing the string prints 'weird characters' means nothing.
char *somevar ... // somevar holds a value in somevar[0] and is null
terminated i.e. somevar[1] = '\0'
At this point you are telling me that somevar[1] holds a null character.
This means that somevar is a string. Doesn't mean it is printable. The
value in somevar[0] must be printable if you want to treat it as a string
you can print.
int a = atoi(somevar);
This will work if somevar[0] is in the range '0' to '9' and it will set a
to 0 through 9, respectively.
However, this is not working. If I try:
int a = (int) somevar[0]; // this works
This will take the binary value of somevar[0] and convert it to an int
then save it in a. For example, if you are on a system that uses ASCII and
the value of somevar[0] is '0' then a will be 48. This is because ASCII
'0' is decimal 48.
My second problem is that I now need to convert this "integer value"
that I just got into a char* to be passed onto some funtion for printing
it out as a string. So I do:
char* b = malloc(sizeof(char)*SOME_LENGTH);
NOTE: sizeof(char) is always 1. So multiplying by sizeof(char) is
pointless.
You also want to be sure the malloc was successful.
b = itoa(a, b, 1);
The itoa function is not standard. Check the FAQ for this newsgroup. There
is a section on itoa and how you should use sprintf instead.
I then print this out. This seems to work fine, but is there a simpler
way of doing this? Thanks :)
Sona
If I understand you correctly, you have somevar[0] = some binary value and
you want to make a string (a) of that value. For example, if somevar[0]==3
then b[]="3". If this is the case, you are making this a LOT harder than
it has to be. Things like atoi, itoa and sprintf are for converting
multiple digit numbers. If you know the number is always one digit then
you can just use math and assignment operators.
--
darrell at cs dot toronto dot edu
or
main(){int j=1234;char t[]=":@abcdefghijklmnopqrstuvwxyz.\n",*i=
"iqgbgxmdbjlgdv.lksrqek.n";char *strchr(const char *,int);while(
*i){j+=strchr(t,*i++)-t;j%=sizeof t-1;putchar(t[j]);} return 0;}