c++中无符号长返回负数
Unsigned long returning negative in C++
下面任何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倍大的数字。这些错误发生在超过
相关文章:
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 在函数中返回无符号字符数组,但不返回指针
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 在函数内初始化无符号字符指针将返回空指针
- 使无符号的 int 值成为有符号的 int 值并返回
- C++ 从函数返回无符号字节
- 如何将 16 位无符号 int 转换为 8 位无符号字符并最终返回无符号字符*?
- 尝试将返回无符号值的函数分配给指向无符号的指针时,继续获取 SIGSEGV
- 对于 ((无符号整数)0-1)返回 true>0
- 无符号函数,用于返回使用任何数字的数字
- 将 C++ 转换为 Python 通过引用返回无符号 char*
- CUDA 纹理无法返回无符号长长长的值类型
- 为什么 std::count_if 返回有符号的值而不是无符号的值
- 从int c++的向量返回一个无符号长
- 为什么(c++)从长-长-无符号int转换为长-双精度并返回生成0
- c++返回无符号字符的数组
- 为什么 shared_ptr<T>::use_count() 返回 long 而不是无符号类型?
- 覆盖从 SHA1 返回到字符串的无符号字符*
- 将无符号 int 转换为字节数组并返回
- 以十六进制值的形式返回无符号字符