Joe Carr Joe Carr - 1 year ago 221
C++ Question

Qt C++ xor for a checksum?

I am trying to find a way of going through a char array with n amount of hexadecimal values i.e {0xA2, 0xE7, 0x5f, 0x1B, 0x11, 0x11, 0x00} and I want to try and do a XOR checksum through all of the items in it - to be more precise the A2 ^ E7 ^ 5F ^ 1B ^ 11 ^ 00 is 10.

Here is the bit of my code:

void MainWindow::checkSum(QByteArray *b)
qint16 b_len = b->length();

unsigned char xor = 0;

for ( int i = 0 ; i < b_len ; i ++ )
xor = xor ^ b[i];

I think my code should be doing the job however qt does not compile it and gives me the silly error of "2248: 'QByteArray::operator QNoImplicitBoolCast' : cannot access private member declared in class 'QByteArray'".

Any ideas on how to make it working?

Answer Source

You are using b as a pointer.

In order to use operator[] (and in general, all operator XX and assignment operators) you should use an object or a reference to an object, not a pointer.

You should modify your function to:

void MainWindow::checkSum(const QByteArray &b)
    //Same code as yours

and your calling should be:

    QByteArray ba;

    //Fill ba.

    //Now you should not pass a pointer
    //checkSum(&ba) //This should be similar to your call.
    checkSum(ba);   //Now, there is no &.

Note: if you want to use opeartor[] with pointers, you should use a different sintax:

void MainWindow::checkSum(QByteArray  *b)
   xor = xor ^ b->operator[](i);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download