Question: Network ip address is given in string form; read that, parse that from left to right; push into integer. 4 parts of ip, each part can be stored in one byte.
Example:
i/p: 172.12.13.14
o/p: 0xCA0C0D0E (0xCA = 172, 0x0C = 12, 0x0D = 13, 0x0E = 14)
Code:
#include<iostream>
using namespace std;
main()
{
char in[20];
int out,i, tmp;
cout <<"enter ip string: " << endl;
cin >> in;
int len = strlen(in);
int place = 3;
out = tmp = 0;
for (i=0; i<len ; i++)
{
if(in[i] == '.')
{
out += tmp << (8*place--);
tmp = 0;
continue;
}
tmp = tmp*10 + in[i] - '0';
}
out = out + tmp;
cout << "IP address is: " << hex << out << endl;
}
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
union ip{
char a[4];
long int add;
} IP;
const char *buf="33.50.1.1";
int a[4];
sscanf(buf,"%d.%d.%d.%d", a,a+1,a+2,a+3);
*(IP.a+0)=(char)(*(a+3));
*(IP.a+1)=(char)(*(a+2));
*(IP.a+2)=(char)(*(a+1));
*(IP.a+3)=(char)(*(a+0));
printf("%x\n", IP);