gpt4 book ai didi

c++ - Unsigned long 在 C++ 中返回负值

转载 作者:行者123 更新时间:2023-11-27 23:17:49 46 4
gpt4 key购买 nike

下面,当任何 numA-D 乘以无数次时,数字突然变成负数。例如,当 numA 乘以 256 3 次时,数字变为负数,但如果仅乘以 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;
}

最佳答案

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

换句话说,这条线

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。

关于c++ - Unsigned long 在 C++ 中返回负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349079/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com