raehee raehee - 3 years ago 227
C++ Question

converting hex into binary in qt

I have to read a raw data from MODbus apps and convert it into hex. In the MODbus, it displays in binary and hex. Lets say I want to read 5 bits =

00011
and when i have converted it to hex it become 0x03 but then when I convert it from hex to binary again. It displays in my UI like this =
11
only, which the 3 remaining zero
000
is disappear. This is my coding:

if (my_arguments.num_of_points <=8)
{
for(int x = 0; x < 1; x++)
{
block33.append(block22[9+x]);
}
}

hexVal = block33.toHex(); //for converting to binary
stringValue = "0x " + block33.toHex().toUpper(); //display hex raw value

QString hexadecimalNumber = hexVal;

bool ok = false;

QString binaryNumber = QString::number(hexadecimalNumber.toLongLong(&ok, 16),2);

ui->textEdit->append(binaryNumber);

ui->textEdit->setText("RawValue in Hex = " + hex_rawValue );


Output =

RawValue in Hex = 03

11 //but i read 5 bits so it should show `00011

Answer Source

Use the QString::arg() overload instead of QString::number(). It has a fieldWidth argument that you can use to fill in the added zeros:

bool ok;
QString hexString = "0x03";
qDebug() << "BINARY 1: " << QString::number(hexString.toLongLong(&ok, 16),2);
qDebug() << "BINARY 2: " << QString("%1").arg(hexString.toULongLong(&ok, 16), 5, 2, QChar('0'));

Output is:

BINARY 1:  "11"
BINARY 2:  "00011"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download