Home > OS >  QString::number result is wrong
QString::number result is wrong

Time:02-02

I was practicing converting numbers in Qt and ran into a problem. I have a variable of type int - result, its value is, for example, 11111 (I get it in a certain way). I want this number to be considered binary in my program. To do this, I'm trying to translate it into a string in variable res and add "0b" in front of my value, like

QString res = "0b"   QString:number(result);

My variable res is "0b11111" and that's right, but I want to get a variable of type int, so I'm trying to cast a string to it:

result = res.toInt();

and in the end I get 0. I understand that this is most likely due to the second character "b", but is there really no way to convert the number to the binary system as it is? Or did I made a mistake somewhere? Thank you for all answers, that could helps me to understand what’s wrong!

CodePudding user response:

With Qt, you can specify the base, if you look carefully at the QString documentation, you could simply write:

res = QString::number(11111);
result = res.toInt(nullptr, 2); // Base 2

Or even better:

bool success; // Can be used to check if the conversion succeeded

res = QString::number(11111);
result = res.toInt(&success, 2);

CodePudding user response:

In order for the QString.toInt() function to use the "C Convention" and determine which base to use according to known prefixes (the "0b" in your case), you need to explicitly specify a base of zero in the call:

QString res = "0b"   QString:number(result);
result = res.toInt(nullptr, 0); // If "base" is zero, parse/use the "0b"

Otherwise, if no "base" argument is given, it will default to 10 (i.e. decimal) and, in that case, only the leading zero in your string will be parsed, because the 'b' character is not a valid decimal digit.

Alternatively, you can skip the leading "0b" characters and explicitly tell the function to use base 2:

QString res = QString:number(result); // No added "0b" prefix
result = res.toInt(nullptr, 2);       // Force use of binary

CodePudding user response:

So you have an integer variables with the value eleven thousand one hundred and eleven, but you want it to be considered binary and therefore a value of thirty one? Can't help thinking that you are solving the wrong problem.

But anyway, convert to a std::string using std::to_string and then use the std::stoi function to convert back to an integer. std::stoi allows you to specify binary a binary conversion.

int result = 11111;
int res = std::stoi(std::to_string(result), nullptr, 2);
std::cout << res << '\n';
  • Related