Solved How to convert a quint32 to QByteArray without leading 00?
-
I have a quint32 with the value of 43. Now I would like to convert it to a QByteArray. I tried it like this:
quint32 newChainIdInt = 43; QByteArray newChainIdArray; QDataStream stream(&newChainIdArray, QIODevice::WriteOnly); stream << newChainIdInt; qDebug() << newChainIdArray.toHex(' ');
I get the following output:
00 00 00 2b
I need to have it without leading 00 00 00. It should look like this:
2b
How can I do this?
-
@Infinity said in How to convert a quint32 to QByteArray without leading 00?:
How can I do this?
Cast the value to an char:
uint32 newChainIdInt = 43; QByteArray newChainIdArray; QDataStream stream(&newChainIdArray, QIODevice::WriteOnly); stream << quint8(newChainIdInt);
-
@KroMignon Thanks. What if the value would be greater than a quint8?
-
@Infinity said in How to convert a quint32 to QByteArray without leading 00?:
What if the value would be greater than a quint8?
It will be lost, of course!
You can also remove zero from QByteArray:uint32 newChainIdInt = 43; QByteArray newChainIdArray; QDataStream stream(&newChainIdArray, QIODevice::WriteOnly); stream << newChainIdInt; while(newChainIdArray.size() > 1 && newChainIdArray[0] == 0) newChainIdArray.remove(0); qDebug() << newChainIdArray.toHex(' ');
-
I use the following piece of code
double value = 43; QByteArray byteArray{ reinterpret_cast<char*>(&value), sizeof(value) };
This should work for anything that is contiguous in memory.