简体   繁体   English

如何在C中连接一个int

[英]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? 我不想将其串联为字符串,而是将其串联为int串联 ,还有其他可能的选择吗?

First of all, what you seem to do is exactly what inet_aton is doing. 首先,您似乎要做的正是inet_aton在做什么。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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