c-将四个整数合并为一



我是C的新手,我正试图将这四个整数组合成一个整数。

srand(time(NULL));
int intOne = 1+rand()%255;
int intTwo = 1+rand()%255;
int intThree = 1+rand()%255;
int intFour = 1+rand()%255;
int allCombined = ("%i.%i.%i.%i", intOne, intTwo, intThree, intFour);
printf("%i", allCombined);

我所需要做的就是将这四个整数组合成一个IP地址格式的变量。

示例:108.41.239.216

如何将它们组合并保存到一个变量中以供以后使用?

有很多方法可以做到这一点,但没有一种方法是正确的。我想到的自然解决方案(在代码片段的上下文中)是将它们存储在长度为4的整数数组中。然后可以分别对它们进行格式化。例如:

int ip_address[ 4 ] = { intOne, intTwo, intThree, intFour };

然后当你想使用它时,它会如下所示:

printf( "%d.%d.%d.%d", ip_address[ 0 ], ip_address[ 1 ], ip_address[ 2 ], ip_address[ 3 ] );

如果您需要访问部分IP地址,这也会给您带来优势,您可以在O(1)中这样做。

这里有几种组合它们的方法:

  1. 将所有四个字节保存为一个无符号的32位整数。第一个字节在0到7位,第二个字节在8到15位,等等
  2. 创建一个包含这四个值的struct。然后可以将它们称为ipAddress.firstOctetipAddress.secondOctet
  3. 创建一个由四个字节组成的数组:ipAddress[0]ipAddress[1]

试试这个:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
  srand(time(NULL ));
  int intOne = 1 + rand() % 255;
  int intTwo = 1 + rand() % 255;
  int intThree = 1 + rand() % 255;
  int intFour = 1 + rand() % 255;
  {
    struct in_addr ia = { 
      (intOne << 0) + (intTwo << 8) + (intThree << 16) + (intFour << 24) /* Here you initialise the integer. */
    };
    printf("0x%x", ntohl(ai.s_addr)); /* Convert the integer to the correct byte order (endianness) and print it. */
    printf("%sn", inet_ntoa(ia)); /* Here you get the dotted version. */
  }
  return 0;
}

最新更新