What is the prefix of a QString for QString::toInt(&ok, 2)?
-
I want to convert a QString to an int with QString::toInt() with the following functions:
bool QStringToInt::setIntString(const QString intString) { m_intNumber = 0; // The input string is in decimal format if (this->stringToInt(intString, 10)) return true; // The input string is in hexadecimal format if (this->stringToInt(intString, 16)) return true; // The input string is in binary format if (this->stringToInt(intString, 2)) return true; qDebug() << "\n"; qDebug() << "QStringToInt::setIntString;"; qDebug().noquote() << "Invalid int string"; return false; } bool QStringToInt::stringToInt(const QString intString, const int base) { bool intStringOk; uint intNumber = intString.toUInt(&intStringOk, base); if (intStringOk) { m_intNumber = intNumber; return true; } else { m_intNumber = 0; return false; } }
Which prefix do I have to put in front of the
intString
thatif (this->stringToInt(intString, 2))
returns true and:
stringToInt(intString, 10) stringToInt(intString, 16)
return false?
If I put "0x" in front of a string,
QString::toInt(&ok, 10)
set ok to false andQString::toInt(&ok, 16)
sets ok to true. Which is good.Which prefix do I have to put in front of the string that
QString::toInt(&ok, 10)
set ok to false,QString::toInt(&ok, 16)
sets ok to false andQString::toInt(&ok, 2)
sets ok to true? -
Those ifs in
::setIntString()
are wrong. You can't detect the base like that. For example0
could be binary, octal, decimal, anything from base 1 up really and all those ifs will returntrue
. It just so happens that you treat it as a base 10 first.QString::toUint
only checks that you don't use invalid digits for given base. It can't detect what base the string is, except for the 3 predefined prefixes, but that only works if you pass 0 as base. Otherwise011
will still be treated as decimal if you pass 10 as base, though it was probably intended as octal. -
Those ifs in
::setIntString()
are wrong. You can't detect the base like that. For example0
could be binary, octal, decimal, anything from base 1 up really and all those ifs will returntrue
. It just so happens that you treat it as a base 10 first.QString::toUint
only checks that you don't use invalid digits for given base. It can't detect what base the string is, except for the 3 predefined prefixes, but that only works if you pass 0 as base. Otherwise011
will still be treated as decimal if you pass 10 as base, though it was probably intended as octal. -
yeah, detecting the base of a number from its string representation is somewhat haphazard unless you are prepared to adopt certain rules and create a parser specifically for that function, such as rules that mimmick the C/C++ numeric literal rules.
0x for hex
0nnn for octal
[1-9][0-9]* for decimal
and i dunno for binary because I always use hex instead