KapursaysHi
KapursaysHi

Reputation: 134

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?

Upvotes: 0

Views: 117

Answers (2)

Werner Henze
Werner Henze

Reputation: 16781

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]);

Upvotes: 5

Doug Currie
Doug Currie

Reputation: 41220

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]

Upvotes: 1

Related Questions