QHostAddress error in convert to string?
I'm confused about QHostAddress class. The following example results in the following output:
int main(int argc, char *argv)
QCoreApplication a(argc, argv);
const QString hostAddress_string1 = "192.168.0.20"; const QString hostAddress_string2 = "192.168.000.020"; QHostAddress hostAddress1; QHostAddress hostAddress2; hostAddress1.setAddress(hostAddress_string1); hostAddress2.setAddress(hostAddress_string2); const QString hostAddress_string12 = hostAddress1.toString(); const QString hostAddress_string22 = hostAddress2.toString(); qDebug() << "String 1 " << hostAddress_string1; qDebug() << "String 12 " << hostAddress_string12; qDebug() << "String 2 " << hostAddress_string2; qDebug() << "String 22 " << hostAddress_string22; return a.exec();
String 1 "192.168.0.20"
String 12 "192.168.0.20"
String 2 "192.168.000.020"
String 22 "192.168.0.16"
I'm using QT 5.5.0. Is this a bug?
That's not a bug. The function apparently converts the string into a literal value (a number). In C/C++ a leading zero indicates an octal value. And 20 octal happens to be 16 in decimal.
You might want to manually convert the string into a number and then pass that number to
QHostAddress::setAddress()to avoid this problem. After all
QHostAddress::setAddress()does its job correctly and the return value will be true.
The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).
... thank you.