PDA

View Full Version : how to get 5 as int from number=QByteArray::fromHex("35");



Tadas
23rd July 2011, 14:05
Hi,

how to get 5 as int from number=QByteArray::fromHex("05");
or how to add 30 as hex to hex value 05, becouse
QByteArray::fromHex("35").toInt(); will give me int as 5

another question


QByteArray number2;
int nubint=3345;
number2= QByteArray::number(nubint).length();
qDebug()<<"number2"<<number2.toHex();
why do I get number2 in hex as 04 in hex, but not as 34 ;

and why i get error message if I will edit 3 line like this number2= QByteArray::number(nubint).length();


error: invalid conversion from 'int' to 'const char*'
error: initializing argument 1 of 'QByteArray& QByteArray::operator=(const char*)'

i'm totally messed up with bits and bytes..

mvuori
23rd July 2011, 23:59
I don't know, but there must be a reason Nokia's Wiki tells that this is done using QString, not QBytearray:
http://www.developer.nokia.com/Community/Wiki/Convert_hexadecimal_to_decimal_and_vice-versa_in_Qt

ChrisW67
24th July 2011, 00:14
QByteArray ba = QByteArray::fromHex("05");
int number = ba.at(0);
qDebug() << number;

number is 5, exactly as you asked for. You are clearly confused between the number 5 and the character '5'. The binary value used to represent these things are not the same (5 and 53 respectively). Take a step back from the solution and explain the problem you are trying to solve.

QByteArray::number() returns a sequence of bytes representing the number in ASCII. The length of that sequence is 4 ("04" in hex).

QByteArray::length() returns an integer and you are trying to store that value into a QByteArray. This is clearly not a perfect match, but the compiler tries to find a way to automatically convert an int to a QByteArray through a conversion constructor, i.e. something like QByteArray::QByteArray(int value), fails and reports the error. The specifics of the error message are because the closest conversion constructor available expects a "const char*" and it cannot convert "int" to that type.