I created a byte array, uint8_t data[256], and I would like to read and write data to it at arbitrary positions. The position offset could be any number, so it could result in an unaligned access. For example if sizeof(int32_t) == 4 then position % sizeof(int32_t) != 0
It works now but, as far as I know, some platforms do not directly support unaligned access. I would like to make it work in that case as well.
#include <cstdint>
#include <iostream>
void write(uint8_t* data, uint32_t position, int32_t value) {
int32_t* ptr = reinterpret_cast<int32_t*>(&data[position]);
*ptr = value;
}
int32_t read(uint8_t* data, uint32_t position) {
int32_t* ptr = reinterpret_cast<int32_t*>(&data[position]);
return *ptr;
}
int main()
{
uint8_t data[256];
int32_t value = 123456789;
uint32_t position = 1; // Example for unaligned access
write(data, position, value);
int32_t read_value = read(data, position);
std::cout << read_value << std::endl;
return 0;
}
I prefer to use the standard library, if there is a solution there for this problem.
std::memcpyto copy the bytes into anint32_t result;, then return thatresult.