Reputation:
below when any of the numA-D is multiplied numerous times the number suddenly becomes a negative. For example when numA is multiplied 3 times by 256 the number then becomes negative,but not if only multiplied by 256 twice. The purpose of this project is to change an ip address to a unsigned long, and then an unsigned long to an ip address.
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;
}
Upvotes: 0
Views: 4060
Reputation: 5250
All integer types are signed
The largest number that can be stored in unsigned was two times higher than signed.
Example:
long val = 2147483647; // Signed max value
unsigned long val = 4294967294; // 2x bigger number can be stored
What if try you to store 4294967294 in signed?
signed long val = 4294967294; // result will be -2
Like i say value in usigned can resive 2x bigger number. These errors occur in the case of exceeding
Upvotes: 0
Reputation: 330
int is 32 bit. it means its max value is 2^31 = 256*256*256*128 - 1. (and its lower value is -2^31)
if numA >=128 it will become negative.
or if numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA) > 2^31 = 2147483648
you will see negative number.
Upvotes: 0
Reputation: 106530
unsigned long
is unsigned -- it can't be negative. But all of your numbers, and as a result all of your calculations, are int
s, not unsigned long
s. int
s are allowed to be negative.
Put another way, this line
rtn = numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA);
Is the same as
rtn = static_cast<unsigned long>(numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA));
All the variables and constants are int
, and they will not be automatically promoted to unsigned long.
Upvotes: 4