简体   繁体   中英

How to convert int to char/string and vice versa in linux(gcc)?

I want to know the method of converting an integer into char/string and vice-versa also.

I have already used sprintf(&charvar,"%d",&intvar) but it produces wrong output, possibly garbage.

i have also heard atoi() in gcc has bugs.Reference: GCC atoi bug

What is the other method to convert string/char back to int?

Actually i want to send an integer from one machine to another using SOCK_STREAM.

//EDIT: I forgot to tell that sprintf() does conversion and returns positive value.

Remove the ampersand before intvar :

sprintf(&charvar,"%d",intvar)

Two notes:

  • Here, I assume that &charvar is of correct type, which it probably isn't.
  • Even though it might not make much difference here, it's a good to get into the habit of using snprintf in preference to sprintf .

Here's some example code:

int intvar = ...;
char str[16];
snprintf(str, sizeof(str), "%d", intvar);

If you want to send an integer to another machine you can send it as binary data, just by sending the intvar directly to the stream, you don't have to convert it to a char first. That will only introduce problems with knowing the length of the data as different values generate different lengths of strings.

Please read the manual of 'sprintf' and 'sscanf', and maybe their safer versions are proper for you.

You cannot sprintf to a variable. You need a buffer for it, because of possible several digits and the trailing zero. Moreover, the argument should be the int variable, not its address.

Example:

char buffer[256];
int i = 42;
sprintf(buffer, "%d", i);

(buffer will be filled with '4', '2' and trailing '\0').

your sprintf is wrong.You should write sprintf(string,"%d",integer); If you want to send an integer over the network and thats why you want to convert it into string have a look at htons

with these functions you can convert an integer to network format and avoid different endianness problems: If you just want to convert it to bytes you can do something like this:

char buf[4];
memcpy(buf,&integer,4);

If you want your string to have the value of the int then you should use sprintf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM