I'm learning socket programming and need to convert data from host byte order(in my case LITTLE ENDIAN) to network byte order. So I need to swap the byte order of the data that I will be sending. So, I used to std::memcpy say integer into a temp char array, then swap the bytes of that temp char array. But now I'm trying to achieve the same using std::reverse_copy but not been able to achieve(not compiling itself). This is my sample code:
#include <iostream>
#include <cstring>
#include <algorithm>
int main()
{
const int a = 0x89ABCDEF;
char arr[sizeof(decltype(a))] {};
char r_arr[sizeof(decltype(a))] {};
std::memcpy(arr, reinterpret_cast<const char*>(&a), sizeof(decltype(a)));
char *start = arr;
char *end = arr + sizeof(decltype(a)) - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
for (int32_t i = 0; i < sizeof(decltype(a)); ++i)
std::cout << std::hex << static_cast<uint16_t>(arr[i]) << std::endl;
// error in below line
// std::reverse_copy(std::begin(reinterpret_cast<const char*>(&a)), std::begin(reinterpret_cast<const char*>(&a)) + sizeof(decltype(a)), std::begin(r_arr));
for (int32_t i = 0; i < sizeof(decltype(a)); ++i)
std::cout << std::hex << static_cast<uint16_t>(r_arr[i]) << std::endl;
return 0;
}
//in front ofstd::reverse_copy..) and the error message