I have the following QByteArray
:
QByteArray ba;
ba.resize(3);
ba[0]=ba[2]=0x8a;
ba[1]=0x0d; //so ba=8a0d8a
I want to add a hexadecimal number to the above QByteArray
. For eg. on adding 0x01, ba
should contain 8a0d8b
. Any such operation involving carry should be propagated forward as in a normal hex addition. I have tried using +
operator:
ba=ba+1;
but it concatenates (resulting in 8a0d8a01
in the above case) instead of performing actual operation. How can this be done ?
I think this is the easiest solution:
uint32_t num = (b[3] << 24) + (b[2] << 16) + (b[1] << 8) + (b[0]);
num++; // add one
b[0] = num & 0xff;
b[1] = (num >> 8) & 0xff;
b[2] = (num >> 16) & 0xff;
b[3] = (num >> 24) & 0xff;
Basically you convert to an arithmetic integer back and forth. Just make sure you don't overflow. This is a simple example. You can make it a class with a state that returns QByteArray
on some method or you can make a function that does this once at a time.