Convert QString in format of Decimal String to appropiate Hex String format.
-
I have below scenario
I have QString for bytesize = 1 , byteSize = 2 byteSize =3
Suppose
QString test("65") ; [for bytesize = 1 i.e char]
I need to convert it to hex string and hex string should contain value (41)How can i do that in QT?
-
@Ayush-Gupta Hi,
QString test("65") ; bool ok = false; quint32 iTest = test.toUInt(&ok, 10); if(ok) { QString hex = QString("%1").arg(iTest, 2, 16); //hex contains now "41" } else { //String to int conversion error }
Shorter version (without testing conversion error)
QString test("65"); QString hex = QString("%1").arg(test.toUInt(), 16);
-
@Ayush-Gupta
QString("65").toLatin1().toHex();
-
@raven-worx said in Convert QString in format of Decimal String to appropiate Hex String format.:
QString("65").toLatin1().toHex();
This gives "3635" and not "41"
-
@Gojir4 said in Convert QString in format of Decimal String to appropiate Hex String format.:
This gives "3635" and not "41"
right, my fault
-
No this does not works for me
consider scenario
QString test("-23") ; //and its of char size then -23 should be representint32 iTest = test.toUInt(&ok, 10);
if(ok) {
QString hex = QString("%1").arg(iTest, 16);
} else {
//String to int conversion error
}is converting on base32 or base32 but I want that it should convert on base8
-
@Ayush-Gupta Of course that's another story if you want to handle negative numbers.
QString strIntToHex(const QString &intStr){ bool ok = false; qint32 iTest = intStr.toInt(&ok, 10); QString hex; if(ok) { if(iTest >= INT8_MIN && iTest <= INT8_MAX){ hex = QString("%1").arg(iTest & 0xFF, 2, 16); } else if(iTest >= INT16_MIN && iTest <= INT16_MAX){ hex = QString("%1").arg(iTest & 0xFFFF, 4, 16); } else { hex = QString("%1").arg(iTest, 8, 16); } } else { //String to int conversion error hex = "error"; } return hex; } QString test("65"); qDebug() << strIntToHex("65"); qDebug() << strIntToHex("-23"); return 0;
Output:
"41" "e9"