1

When I convert following bytes which are received from TCP communication, I get 0 in QT and 32.097133442517112 in C#.NET. How can I resolve this issue in QT?

C# .NET

byte[] data = {0xbd, 0x7a, 0x5f, 0xde, 0x6e, 0x0c, 0x40, 0x40};
double value = BitConverter.ToDouble(data, 0); // value is 32.097133442517112

C++ QT

QByteArray *arr = new QByteArray();
arr->append(0xbd);
arr->append(0x7a);
arr->append(0x5f);
arr->append(0xde);
arr->append(0x6e);
arr->append(0x0c);
arr->append(0x40);
arr->append(0x40);
double value = arr->toDouble(); // value is 0

EDIT: Following snippet seems to work ok. It gives the result as 32.0971.

union {
    double d;
    char bytes[sizeof(double)];
} u;

u.bytes[0]=0xbd;
u.bytes[1]= 0x7a;
u.bytes[2]=0x5f;
u.bytes[3]=0xde;
u.bytes[4]=0x6e;
u.bytes[5]=0x0c;
u.bytes[6]= 0x40;
u.bytes[7]=0x40;
qDebug()<<u.d; // result 32.0971

Should I continue with this, or are there any QT side solution for that?

mtekeli
  • 705
  • 1
  • 7
  • 17
  • @Ian It outputs again 0 when I reversed the bytes in array. – mtekeli Mar 09 '16 at 08:43
  • @Ian I have QByteArray and want the number value. However QByteArray::number gets a number and returns as QByteArray. I didn't get the point. – mtekeli Mar 09 '16 at 08:52
  • @Ian Tried with both QByteArray dbl("BD7A5FDE6E0C4040") and QByteArray dbl("40400C6EDE5F7ABD") and the same result, success is false, return 0. – mtekeli Mar 09 '16 at 09:02

2 Answers2

0

i think the QByteArray::toDouble() does only work for readable double values (like 3.14) so Converting char * to double while reading from binary file in C++? should give you a hint on how it could be done

Community
  • 1
  • 1
Zaiborg
  • 2,492
  • 19
  • 28
0

Ok, QDataStream does it:

double value2;
QDataStream stream(*arr);
stream.setByteOrder(QDataStream::LittleEndian);
stream >> value2; // value2 is 32.097133442517112

Thanks for those who contributed.

mtekeli
  • 705
  • 1
  • 7
  • 17