c++中无符号长返回负数

Unsigned long returning negative in C++

本文关键字:返回 无符号 c++      更新时间:2023-10-16

下面任何numA-D乘以无数次,数字突然变成负数。例如,当numA乘以256 3次时,数字变为负数,但如果只乘以256两次则不会。本项目的目的是将ip地址更改为无符号长地址,然后将无符号长地址更改为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;
}

unsigned long是无符号的——它不能是负的。但是你所有的数字,结果你所有的计算,都是int s,而不是unsigned long s。int s允许为负

换句话说,这行

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,它们不会被自动提升为unsigned long

int为32位。这意味着它的最大值是2^31 = 256*256*256*128 - 1。(其下限为-2^31)
如果numA>=128,它将变为负值。
或者如果numD + (256 * numC) + (256 * 256 * numB) + (256 * 256 * numA)> 2^31 = 2147483648

所有的整数类型都有符号

  • LONG -无符号总是有符号- 2,147,483,648至2,147,483,647
  • INT -无符号总是有符号- 2,147,483,648至2,147,483,647
  • SHORT -无符号总是有符号- 32,768至32,767
  • FLOAT -无符号总是带符号3.4E +/- 38(7位)
  • DOUBLE -无符号总是带符号1.7E +/- 308(15位)

unsigned类型中可存储的最大数值是signed类型的2倍。

例子:

long val = 2147483647; // Signed max value
unsigned long val = 4294967294;  // 2x bigger number can be stored

如果尝试将4294967294存储在signed中会怎么样?

signed long val = 4294967294;  // result will be -2

就像我说的,ussigned中的值可以倒退2倍大的数字。这些错误发生在超过

的情况下。