Search code examples
c++qtqstring

Parse number from string with optional base


How can I parse numbers like 0x345, 23423, 0172 (possibly also 0b001111) from strings?

I found the regular QString::toXXX functions but they take a base argument, but i want the base to be determined from the string in a way as it a C-Compiler would do.

I think there must be something present in Qt. But I only found the above mentioned or other method that explicitly take base (e.g. as stream manipulator).

Thank you in advance.


Solution

  • The QString::toXXX do what you want (except the binary representation):

    If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

    So just use int i = s.toInt(NULL, 0);