Quick Way to Find the Sum or Average of All Elements in QByteArray

Posted on Posted in Qt Tutorials, Tutorials

There are scenarios where you would need to find the sum or the average of all values in a QByteArray. This can specially happen if you are trying to send data using COM ports to devices that require the average or sum (or a similar combination) of all elements in order to check the integrity of data.

Here is how you can use STL functions to quickly find the sum of all elements in a QByteArray (or QString)

Function std::accumulate can be used for this purpose:

QByteArray b;
int sum = 0;
sum = std::accumulate(b.begin(), b.end(), sum);
qDebug() << sum; // 548
qDebug() << sum / b.size(); // Average = 68
qDebug() << char(sum / b.size()); // Average Character = D

Leave a Reply

Your email address will not be published. Required fields are marked *