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
11
000
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 );
RawValue in Hex = 03
11 //but i read 5 bits so it should show `00011
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"