C语言练习笔记~指针7~将 ip 地址转化为整数

#include 

int main (void)
{
   char a[] = "192.168.2.5";
   unsigned int ip = 0;
   unsigned char *p = (unsigned char *)&ip;
   int a1, a2, a3, a4;
   sscanf (a,"%d.%d.%d.%d",&a1, &a2, &a3, &a4);
   //printf("%d, %d, %d, %d\n",a1,a2,a3,a4 );
   /*
   //法一
   p[0] = a4;
   p[1] = a3;
   p[2] = a2;
   p[3] = a1;
  */

  //法二
  *p = a4;
  p++;
  *p = a3;
  p++;
  *p = a2;
  p++;
  *p = a1;

   printf("%u\n",ip);

   return 0;

}

输出结果:
C语言练习笔记~指针7~将 ip 地址转化为整数_第1张图片

你可能感兴趣的:(C语言)