0

I am wondering what the most efficient way would be to convert a binary that is saved as a QString into the corresponding Hex and save it in the same QString

QString value = "10111100" 

into

value = "bc"
3
  • Binary strings can be converted to hexadecimal strings trivially by considering that 4 bits are mapped straight to one hexadecimal digit. You have to work a bit if your string length is not multiple or 4, but it's not complicated to write something that processes that efficiently even working from left to right (to avoid prepending data to the target string or inverting it at the end). Commented Jul 22, 2018 at 12:28
  • @MatteoItalia That's good general advice. But then, most anything C-based will include selectable base when converting to integers from strings. So, strol() in C lets you select the base, C++ streams do, Qt's QString::toInt does, etc. Commented Jul 22, 2018 at 17:39
  • @KubaOber it depends wheheter you want to handle arbitrarily long strings. Also, he asked for the most efficient way... Commented Jul 22, 2018 at 18:05

1 Answer 1

1

It's simple. First convert your binary string to an integer:

QString value = "10111100";
bool fOK;
int iValue = value.toInt(&fOk, 2);  //2 is the base

Then convert the integer to hex string:

value = QString::number(iValue, 16);  //The new base is 16
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.