QByteArray to integer - qt

As you may have figured out from the title, I'm having problems converting a QByteArray to an integer.
QByteArray buffer = server->read(8192);
QByteArray q_size = buffer.mid(0, 2);
int size = q_size.toInt();
However, size is 0. The buffer doesn't receive any ASCII character and I believe the toInt() function won't work if it's not an ASCII character. The int size should be 37 (0x25), but - as I have said - it's 0.
The q_size is 0x2500 (or the other endianness order - 0x0025).
What's the problem here ? I'm pretty sure q_size holds the data I need.

Something like this should work, using a data stream to read from the buffer:
QDataStream ds(buffer);
short size; // Since the size you're trying to read appears to be 2 bytes
ds >> size;
// You can continue reading more data from the stream here

The toInt method parses a int if the QByteArray contains a string with digits. You want to interpret the raw bits as an integer. I don't think there is a method for that in QByteArray, so you'll have to construct the value yourself from the single bytes. Probably something like this will work:
int size = (static_cast<unsigned int>(q_size[0]) & 0xFF) << 8
+ (static_cast<unsigned int>(q_size[1]) & 0xFF);
(Or the other way around, depending on Endianness)

I haven't tried this myself to see if it works but it looks from the Qt docs like you want a QDataStream. This supports extracting all the basic C++ types and can be created wth a QByteArray as input.

bool ok;
q_size.toHex().toInt(&ok, 16);
works for me

I had great problems in converting serial data (QByteArray) to integer which was meant to be used as the value for a Progress Bar, but solved it in a very simple way:
QByteArray data = serial->readall();
QString data2 = tr(data); //converted the byte array to a string
ui->QProgressBar->setValue(data2.toUInt()); //converted the string to an unmarked integer..

This works for me:
QByteArray array2;
array2.reserve(4);
array2[0] = data[1];
array2[1] = data[2];
array2[2] = data[3];
array2[3] = data[4];
memcpy(&blockSize, array2, sizeof(int));
data is a qbytearray, from index = 1 to 4 are array integer.

Create a QDataStream that operates on your QByteArray. Documentation is here

Try toInt(bool *ok = Q_NULLPTR, int base = 10) const method of QByteArray Class.
QByteArray Documentatio: http://doc.qt.io/qt-5/QByteArray.html

Related

How can i convert a QByteArray into a hex string?

I have the blow QByteArray.
QByteArray ba;
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;
I have really no idea how to convert this QByteArray into resulted string which have "01100007", which i would use the QRegExp for pattern matching on this string?
First of all, the QByteArray does not contain "hex values", it contains bytes (as it's name implies). Number can be "hex" only when it is printed as text.
Your code should be:
QByteArray ba(4, 0); // array length 4, filled with 0
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;
Anyway, to convert a QByteArray to a hex string, you got lucky: just use QByteArray::toHex() method!
QByteArray ba_as_hex_string = ba.toHex();
Note that it returns 8-bit text, but you can just assign it to a QString without worrying much about encodings, since it is pure ASCII. If you want upper case A-F in your hexadecimal numbers instead of the default a-f, you can use QByteArray::toUpper() to convert the case.
QString has following contructor:
constructor QString(const QByteArray &ba)
But note that an octal number is preceeded by 0 in c++, so some of your values are deciamal, some octal, none of them are hex.

How to convert double* data to const char* or QByteArray efficiently

I am trying to use the network programming APIs in Qt in my project. One part of my code requires me to convert double* data to QByteArray or a const char*.
I searched through the stackoverflow questions and could find many people suggesting this code :
QByteArray array(reinterpret_cast<const char*>(data), sizeof(double));
or, for an array of double :
QByteArray::fromRawData(reinterpret_cast<const char*>(data),s*sizeof(double));
When I use them in my function, It does notgive me the desired result. The output seems to be random characters.
Please Suggest an efficient way to implement it in Qt. Thank you very much for your time.
Regards
Alok
If you just need to encode and decode a double into a byte array, this works:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray(reinterpret_cast<const char*>(&value), sizeof(double));
// Decode the value
double outValue;
// Copy the data from the byte array into the double
memcpy(&outValue, byteArray.data(), sizeof(double));
printf("%f", outValue);
However, that is not the best way to send data over the network, as it will depend on the platform specifics of how the machines encode the double type. I would recommend you look at the QDataStream class, which allows you to do this:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << value;
// Decode the value
double outValue;
QDataStream readStream(&byteArray, QIODevice::ReadOnly);
readStream >> outValue;
printf("%f", outValue);
This is now platform independent, and the stream operators make it very convenient and easy to read.
Assuming that you want to create a human readable string:
double d = 3.141459;
QString s = QString::number(d); // method has options for format and precision, see docs
or if you need localization where locale is a QLocale object:
s = locale.toString(d); // method has options for format and precision, see docs
You can easily convert the string into a QByteArray using s.toUtf8() or s.toLatin1() if really necessary. If speed is important there also is:
QByteArray ba = QByteArray::number(d); // method has options for format and precision, see docs

Get a string representation of a single byte from QByteArray?

I have a QByteArray i create manually:
QByteArray hexArray(QByteArray::fromHex("495676"));
If this was encoded ASCII it would be "IVv".
If I want to get a single byte of data from that array.
I can do that like this:
qDebug() << messageToBeSent_raw[0];
However, that outputs I, which is correct but I would like to get 49. What I'm looking for is an equivalent of the QByteArray::toHex() just for a single byte. Is there a way to do it?
You can use QString::number.
qDebug() << QString::number(hexArray[0], 16);

how to print a uint16 monochrome image in Qt?

I'm trying to print a image from a Dicom file. I pass the raw data to a convertToFormat_RGB888 function. As far as I know, Qt can't handle monochrome 16 bits images.
Here's the original image (converted to jpg here):
http://imageshack.us/photo/my-images/839/16bitc.jpg/
bool convertToFormat_RGB888(gdcm::Image const & gimage, char *buffer, QImage* &imageQt)
Inside this function, I get inside this...
...
else if (gimage.GetPixelFormat() == gdcm::PixelFormat::UINT16)
{
short *buffer16 = (short*)buffer;
unsigned char *ubuffer = new unsigned char[dimX*dimY*3];
unsigned char *pubuffer = ubuffer;
for (unsigned int i = 0; i < dimX*dimY; i++)
{
*pubuffer++ = *buffer16;
*pubuffer++ = *buffer16;
*pubuffer++ = *buffer16;
buffer16++;
}
imageQt = new QImage(ubuffer, dimX, dimY, QImage::Format_RGB888);
...
This code is a little adaptation from here:
gdcm.sourceforge.net/2.0/html/ConvertToQImage_8cxx-example.html
But the original one I got a execution error. Using mine at least I get an image, but it's not the same.
Here is the new image (converted to jpg here):
http://imageshack.us/photo/my-images/204/8bitz.jpg/
What am I doing wrong?
Thanks.
Try to get values of pixels from buffer manually and pass it to QImage::setPixel. It can be simplier.
You are assigning 16-bit integer to 8-bit variables here:
*pubuffer++ = *buffer16;
The result is undefined and most compilers just move the lower 8 bits to the destination. You want the upper 8 bits
*pubuffer++ = (*buffer16) >> 8;
The other issue is endianness. Depending to the endianness of the source data, you may need to call one of the QtEndian functions.
Lastly, you don't really need to use any of the 32 or 24-bit Qt image formats. Use 8-bit QImage::Format_Indexed8 and set the color table to grays.

How to convert QList<QByteArray> to QString in QT?

I have a QList<QByteArray> that I want to print out in a QTextBrowser. QTextBrowser->append() takes a QString.
Despite a ton of searching online, I have not found a way to convert the data I have into a QString.
There are several functions to convert QByteArray to QString: QString::fromAscii(), QString::fromLatin1(), QString::fromUtf8() etc. for the most common ones, and QTextCodec for other encodings. Which one is the correct one depends on the encoding of the text data in the byte array.
Try:
for(int i=0; i<list.size(); ++i){
QString str(list[i].constData());
// use your string as needed
}
from QByteArray to QString, do
const char * QByteArray::constData () const
Returns a pointer to the data stored in the byte array. The pointer
can be used to access the bytes that compose the array. The data is
'\0'-terminated. The pointer remains valid as long as the byte array
isn't reallocated or destroyed.
This function is mostly useful to pass a byte array to a function that
accepts a const char *.
you then have this QString constructor
QString ( const QChar * unicode )

Resources