PDA

View Full Version : conversion from bytearray to int produce zero



daemonna
11th August 2010, 22:21
hi,
can someone help me coz my conversion from socket stream doesnt work (or maybe i'm just blind).. thanks in advance



qDebug() << "server sending auth question!!!";
qDebug() << sockdata.toHex();
qDebug() << sockdata.mid(2, 1).toHex() << ":" << sockdata.mid(3, 1).toHex() << ":" << sockdata.mid(4.1).toHex();
bool ok;
quint8 res;
int num1=sockdata.mid(2, 1).toInt(&ok, 10);
int num2=sockdata.mid(3, 1).toInt(&ok, 10);
int oper=sockdata.mid(4, 1).toInt(&ok, 10);
qDebug() << "num1 " << num1 << " num2 " << num2 << " op " << oper;


and i get zeroes


server sending auth question!!!
"ffdecb7002"
"cb" : "70" : "02"
num1 0 num2 0 op 0
result: 0 "ffdf00000000"
"ffdf00000000"

daemonna
11th August 2010, 22:25
and btw. on Hex base it doesnt work either, so it's really something wrong with my conversion toInt...

Lykurg
11th August 2010, 23:04
What's about
bool ok;
QByteArray ba = QByteArray::fromHex("ffdecb7002");
qWarning() << ba.toHex();
qWarning() << ba.mid(2,1).toHex() << ba.mid(2,1).toHex().toInt(&ok, 16);
gives
"ffdecb7002"
"cb" 203 ..or say what you expect.

ChrisW67
11th August 2010, 23:52
I assume that you are expecting to see:

"cb" : "70" : "02"
num1 203 num2 112 op 2

in which case this is where you come unstuck:


int num1=sockdata.mid(2, 1).toInt(&ok, 10);
int num2=sockdata.mid(3, 1).toInt(&ok, 10);
int oper=sockdata.mid(4, 1).toInt(&ok, 10);

You are telling Qt that the QByteArray containing the single byte '0xcb' is an ASCII string of a number in base 10. When it tries to convert that to an int if fails: 0xcb is not an ASCII digit 0-9. The result is 0 and ok will be false (you don't check).
Try:


int num1 = (unsigned char) sockdata.at(2);
int num2 = (unsigned char) sockdata.at(3);
int oper = (unsigned char) sockdata.at(4);