Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Convert double to qbytearray
I have a variable defined as a double which I want to write that as binary to a blob field in sqlite. The sqlite api expects a QByteArray of the data to write to the field.
double xValue = 70.976;
hex value of xValue is: 0x428df3b6
The resulting blob should look something like:
blobData is 0x42 (01000010)
blobData is 0x8d (10001101)
blobData is 0xf3 (11110011)
blobData is 0xb6 (10110110)
How do I copy the xValue onto the end of the blobData QByteArray in binary form?
QByteArray::number comes to mind.
A double value is not only 4 bytes long...
@Christian-Ehrlicher True that. But, they would have 0's for the other 4 bytes.
@SGaist That's what I started with:
What that does is write text to the field like a text field "70.976." That's not quite what I was hoping for.
True that. But, they would have 0's for the other 4 bytes.
No, you're wrong. The byte representation you're showing in your first post is the float value of 70.976.
float f = 70.976; const unsigned char *ptr = (const unsigned char*)(&f); for (int i = 0; i < 4; ++i) fprintf(stderr, "%02x\n", ptr[i]); fprintf(stderr, "\n"); double d = 70.976; const unsigned char *ptr2 = (const unsigned char*)(&d); for (int i = 0; i < 8; ++i) fprintf(stderr, "%02x\n", ptr2[i]);
b6 f3 8d 42 58 39 b4 c8 76 be 51 40
@Christian-Ehrlicher Oh, I see what you're saying. And, in the process you showed me a way I may be able to do what I want. Once I have a const usigned char* to the xValue, I should be able to add 8 bytes to the blobData and then use memcpy to copy the bytes directly.
I'm working from home right now and can't get to the office to turn on the laser to test it fully, but this is what I'm thinking:
const unsigned char* dPtr = nullptr;
dataSize = blobData.length();
blobData.append(16, ' ');
dPtr = reinterpret_cast<const unsigned char*>(&xValue);
memcpy(outData.data()+dataSize, dPtr, 8);
Thank you again for the help.
Out of curiosity, why are you storing a double value as a blob in your database ?
Daniel Williams last edited by Daniel Williams
@SGaist I get about 1040 x and a z values from the sdk that pulls the data from the laser device. Each tuple represents a point. x is the position on the laser line and z is the height at that point. I store each tuple consecutively in the blob. Then, the program that renders the image pulls the data from the blob and does the processing and display of the image.
Each 1040 points represents 1 line. I get thousands of lines in a matter of seconds. Each line is a row in the database. Each row in the database thus represents the y axis of a 3-dimensiaonal image.
fcarney last edited by
Isnt this what QDataStream is for?