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.