Convert QByteArray to int
-
Hi,
I have QByteArray like below:
"\x00\x00\x00\x00\x02\x00"
How convert above array to int value = 200 ?In this way :
.toInt(nullptr,10)
doesn't work. -
@Axel-Spoerl said in Convert QByteArray to int:
Check out how int 200 was converted into bytes and then implement a reverse conversion.
I do like below:
QByteArray buf1 = "000000002000" QByteArray buf2 = QByteArray::fromHex(buf1);
Consequently in buf2 I have
"\x00\x00\x00\x00\x02\x00"
So,to reverse conversion I do:
quint16 val = buf2.toHex().toInt(nullptr,10);
-
@Damian7546
This code parses the byte array as a string with digits. That’s why it doesn’t work.Maybe I overlook something, but I see hex 000000200, which would be an int value of 512, not 200.
Check out how int 200 was converted into bytes and then implement a reverse conversion.
-
This post is deleted!
-
basic C language coding: Qt/QByteArray is not required, nor warranted
uint8_t array[] = { 0x00U, 0x00U, 0x02U, 0x00U }; uint32_t hostValue = ntohl(*(uint32_t*)array); // should return 0x200U, but beware some architectures don't like // dereferencing raw memory as an aritrary type unless guarantees // are made that the data is native aligned with the expected data type
A workaround is:
uint32_t source = 0UL; // source will be properly aligned memcpy(&source, array, sizeof(uint32_t)); uint32_t hostValue = ntohl(source);
-
@Axel-Spoerl said in Convert QByteArray to int:
Check out how int 200 was converted into bytes and then implement a reverse conversion.
I do like below:
QByteArray buf1 = "000000002000" QByteArray buf2 = QByteArray::fromHex(buf1);
Consequently in buf2 I have
"\x00\x00\x00\x00\x02\x00"
So,to reverse conversion I do:
quint16 val = buf2.toHex().toInt(nullptr,10);
-
-
@Damian7546 said in Convert QByteArray to int:
quint16 val = buf2.toHex().toInt(nullptr,10);
No, since toInt() converts readable characters written as integers, not binary stuff - please read the documentation.