Unsolved convert HEX to double
-
I want to convert LineEdit contents(HEX value) to double and this is my code:
void settings::on_pb2_clicked() { QString s = QString::number(ui->lineEdit_Temp1_Read->text().toDouble()); ui->lineEdit_Temp1_Read->setText(s); qDebug()<< s; }
but if the LineEdit contents include characters like A, B, C, D, E, F the content is changed to zero when click on pb2
how can I convert it's contents to double?
-
@rezaMSLM please give an example input and the expected output.
-
You need to use a conversion function with hex-support, not available for doubles...
So, you have to- convert the String to int/long/longlong with
e.g. QString::.toInt(bool *ok = NULLPTR, int base = 10) called with base =16 - convert the resulting value to double if ok is true
Anyway, setting the resulting value back into your lineEdit seems not to be the best idea...
- convert the String to int/long/longlong with
-
is there any method in qt to do this?
-
@rezaMSLM so in principle the same as in https://forum.qt.io/topic/74412/qbytearray-to-float-value
You just need to convert the hex string
toUInt()
first, with the base 16. -
@rezaMSLM
have you tried the following?QByteArray::fromHex(hex).toDouble()
i haven't tested this though.
-
@raven-worx That will not work, as
toDouble()
expects the data to be in ASCII, e.g. "1.234E+5". -
@aha_1980
right, my fault.
This method rather does string parsing. -
-
@rezaMSLM said in convert HEX to double:
is there any method in qt to do this?
If the hex sequence matches your computer's endianness, then you can convert the hex string to the corresponding bytes and tell your CPU to interpret the bytes as a
double
value:QByteArray hexStr = ui->lineEdit_Temp1_Read->text().toUtf8(); QByteArray bytes = QByteArray::fromHex(hexStr); double *ptr = reinterpret_cast<double*>( bytes.data() ); double value = *ptr;