I've got a quick and I am assuming question but I have not been able to find anything online.
How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
I've got a quick and I am assuming question but I have not been able to find anything online.
How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
C++03 and C++0x:
#include <numeric>
int count = sizeof(arr)/sizeof(arr[0]);
int sum = std::accumulate<unsigned char*, int>(arr,arr + count,0);
double average = (double)sum/count;
Online Demo : http://www.ideone.com/2YXaT
C++0x Only (using lambda)
#include <algorithm>
int sum = 0;
std::for_each(arr,arr+count,[&](int n){ sum += n; });
double average = (double)sum/count;
Online Demo : http://www.ideone.com/IGfht
About like with anything else, you add them up and divide by the count. To avoid overflow, you'll typically want to convert them to something larger while you're doing the math. If (as is common) you want a floating point result, you'll want to do all the math on floating point as well.
Arithmetic operations work just fine on unsigned char
, although you may occasionally be surprised by the fact that arithmetic in C always promotes to int
.
In C++'s Standard Template Library,
#include <numeric>
template<class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init);
To calculate the sum of unsigned char arr[]
, you may use accumulate(arr, arr + sizeof(arr) / sizeof(arr[0]), 0)
. (0 is an int
here. You may find it more appropriate to use a different type.)
Without STL, this is trivially computed with a loop.
The average is the sum divided by the length (sizeof(arr) / sizeof(arr[0])
).