下面当任何 numA-D 乘以无数次时,这个数字突然变成负数。例如,当 numA 乘以 3 乘以 256 时,该数字变为负数,但如果仅乘以 256 两次则不会。该项目的目的是将一个 ip 地址更改为 unsigned long,然后将 unsigned long 更改为 ip 地址。
using namespace std;
unsigned long ip2long (string ipv4)
{
// variable to return
unsigned long rtn;
string A,B,C,D;
string delimiter = ".";
size_t position;
/* must parse string by '.' character
and then assign (A,B,C,D) to the values
and return the unsigned long last, you don't have to make
the variables unsigned longs */
int locOfA = ipv4.find('.' );
int locOfB = ipv4.find('.', locOfA + 1);
int locOfC = ipv4.find('.', locOfB + 1);
int locOfD = ipv4.find('.', locOfC + 1);
A = ipv4.substr(0,locOfA);
B = ipv4.substr(locOfA + 1, locOfB - locOfA - 1);
C = ipv4.substr(locOfB + 1, locOfC - locOfB -1 );
D = ipv4.substr(locOfC + 1, locOfD - locOfC -1);
int numA = atoi(A.c_str());
int numB = atoi(B.c_str());
int numC = atoi(C.c_str());
int numD = atoi(D.c_str());
cout << endl;
cout << numA << endl;
cout << numB << endl;
cout << numC << endl;
cout << numD << endl;
cout << endl;
// assigning a unsigned long to the sum of the algorithm
cout << (numA * 256 * 256) + << endl;
cout << (256 * 256 * 256 * numB) << endl;
cout << (256 * numC) << endl;
cout << (256 * numD) << endl;
rtn = numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA);
return rtn;
}