C ++中的无符号长返回否定

时间:2013-03-11 21:33:18

标签: c++ negative-number unsigned-long-long-int

下面当任何一个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;
}

3 个答案:

答案 0 :(得分:4)

unsigned long是无符号的 - 它不能是否定的。但是,您的所有数字,以及所有计算结果都是int s,而不是unsigned long s。 int被允许为否定。

换句话说,这一行

rtn = numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA);

相同
rtn = static_cast<unsigned long>(numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * 256 * numA));

所有变量和常量都是int,它们不会自动提升为无符号长。

答案 1 :(得分:0)

int是32位。它表示其最大值为2 ^ 31 = 256 * 256 * 256 * 128 - 1.(其下限值为-2 ^ 31)
如果numA> = 128,它将变为负数 或者如果numD +(​​256 * numC)+(256 * 256 * numB)+(256 * 256 * 256 * numA)&gt; 2 ^ 31 = 2147483648
   你会看到负数。

答案 2 :(得分:0)

所有整数类型都已签名

  • LONG - Whitout unsigned总是签名-2,147,483,648到2,147,483,647
  • INT - Whitout unsigned始终签名为-2,147,483,648至2,147,483,647
  • 简短 - Whitout unsigned始终签名为-32,768至32,767
  • FLOAT - Whitout unsigned总是签名为3.4E +/- 38(7位数)
  • DOUBLE - Whitout unsigned始终签名为1.7E +/- 308(15位)

可以存储在unsigned中的最大数字是签名的两倍。

示例:

long val = 2147483647; // Signed max value

unsigned long val = 4294967294;  // 2x bigger number can be stored

如果您尝试将4294967294存储在签名?

中,该怎么办?
signed long val = 4294967294;  // result will be -2

就像我说的那样,使用中的价值可以减少2倍的数量。在超过

的情况下会发生这些错误