简体   繁体   中英

How to concatenate an int in c

So I have this code

char str[80] = "192.168.12.142";
char string[80];
char s[2] = ".";
char *token;
int val[4];
int counter=0;
/* get the first token */
token = strtok(str, s);

/* walk through other tokens */
while( token != NULL ){

  val[counter] = atoi(token);
  token = strtok(NULL, s);
  counter++;
}


sprintf(string,"%d.%d.%d.%d",val[0],val[1],val[2],val[3]);
puts(string);

Instead of concatenate it into an string, I want to concatenate it to an int concatenation , is there any possibly alternative?

First of all, what you seem to do is exactly what inet_aton is doing. You might consider using this function.

Regarding the concatenation you can write

int result = (val[3] << 24) | (val[2] << 16) | (val[1] << 8) | (val[0]);

or, for the opposite byte order:

int result = (val[0] << 24) | (val[1] << 16) | (val[2] << 8) | (val[3]);

You probably want

(((((val[0] << 8) + val[1]) << 8) + val[2]) << 8 ) + val[3]

Or equivalently

(val[0] << 24) | (val[1] << 16) | (val[2] << 8) | val[0]

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