I have an array like this one below:
std::array<char, 10> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
I have to add 2 more bytes that would represent the checksum of the array.
The checksum is calculated like this:
char x = 0;
char y = 0;
for (int i = 0; i < size; i++)
{
x = x + array[i];
y = x + y;
}
Finally, the values x and y should be added at the end array.
I want the array to be static inside a method of a class. I don't know if that matters.
class Foo
{
public:
char * getData(void)
{
static std::array<char, 10> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// checksum must be calculated here.
return &numbers[0];
}
}
If I leave two extra bytes space in the array and pass it by reference in a constexpr function. Would that work?
constexpr void checksum_calc(std::array<char, 12>& arr)
{
char x = 0;
char y = 0;
for (int i = 0; i < 12 - 2; i++)
{
x = x + array[i];
y = x + y;
}
arr[10] = x;
arr[11] = y;
}
Also, if I want the array to work on different sizes, can I make it a template?
Like this?
template <size_t sz>
constexpr void checksum_calc(std::array<char, sz>& arr)
{
char x = 0;
char y = 0;
for (int i = 0; i < sz - 2; i++)
{
x = x + array[i];
y = x + y;
}
arr[sz - 2] = x;
arr[sz - 1] = y;
}
Example:
char * getData()
{
// two extra bytes for the checksum
static std::array<char, 12> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
checksum_calc<12>(numbers);
return &numbers[0];
}
The reason I chose a template is because I want arrays of different sizes like:
Example 2:
char * foo_getData()
{
// two extra bytes for the checksum
static std::array<char, 7> numbers = {1, 2, 3, 4, 5};
checksum_calc<7>(numbers);
return &numbers[0];
}
char * bar_getData()
{
// two extra bytes for the checksum
static std::array<char, 9> numbers = {1, 2, 3, 4, 5, 6, 7};
checksum_calc<9>(numbers);
return &numbers[0];
}
The purpose is to have a constant array followed by 2 bytes checksum that must be calculated.
I don't want to calculate it by hand and add it.
Is what I'm trying to do a good practice?
numbersarray is constexpr, you can create another constexpr likenumbers_with_chksumwith the checksum but you can't just change the size of astd::arrayafter the fact whether constexpr or not.static std::array<char, 12> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0};or similar with 2 extra entries for the checksum in place ofstatic std::array<char, 10> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};?constexprfunction at compile time. I want to populate the 2 last positions of the array at compile time, since all bytes are known. Can I do that?constexprfunctions to be executed at compile time, they merely may be executed at compile time if they called not in constant expression, so in complex situations they can be executed at runtime.