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!
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);