PDA

View Full Version : Extracting int values from QByteArray



Tottish
6th April 2010, 15:53
Hello!
I've got a problem that is most likely an easy fix for a lot of you but I've been sitting here with this for more than two hours now so I'm reaching out to ya'll! =)

I have used the sreader example of the QSerialDevice to get receive some data from a microcontroller so I have a QByteArray with five bytes in it.
Now I simply want to get the decimal representation of the five bytes (0-255) in an integer array or separate ints.
I could describe to you the methods I tried to use so far but I don't see the point as none of them worked.

Have a good one, people!
/Tottish

toutarrive
6th April 2010, 17:05
Have look at http://stackoverflow.com/questions/1251662/qbytearray-to-integer

Tottish
7th April 2010, 08:48
Hmm, I'm not sure what to make of that. The most popular solution seems to be using QDataStream but isn't that kind of a detour? Why can't I just extract a decimal representation from the ByteArray?
Something like this:

QByteArray ba = MyDevice->read(readBytes)
int myInt = ba[1]

The closest that I've come is to get a 1-128 positive and negative (signed 8-bit?) but that is with quite ugly code and of course I could write an algorithm to convert this to a 0-255 representation but surely there is some really simple syntax to fix this???

Regards
/Tottish

ChrisW67
7th April 2010, 09:41
You want to access the bytes individually?


QByteArray ba(10, '\xaa');
qDebug() << "Byte is "<< static_cast<quint8>(ba[5]);

Tottish
7th April 2010, 10:41
Thanks ChrisW67!

It was the static_cast<quint8> that was the missing piece in my puzzle!

Thanks a lot! I owe you one! =)
Have a wonderful day, people!
/Tottish