I am converting a boost::asio::ip::address_v6
IP (say 1456:94ce:2567:a4ef:1356:94de:2967:a4e8
) first into 16 bytes unsigned char
array by doing the following :
auto ip = boost::asio::ip::address_v6::from_string("1456:94ce:2567:a4ef:1356:94de:2967:a4e8");
auto v6Bytes = ip.boost::asio::ip::address_v6::to_bytes();
Now my next objective is to use 8 bytes from the byte array and convert them into uint64_t
(say I get num1
). Similarly, using the next 8 bytes from the array, I want to generate another uint64_t
(say num2
). What logic can I use here for conversion?
Also, once I get num1
and num2
, I want to use them and convert back to a
std::array<unsigned char, 16>
What logic can I use here?
答案 0 :(得分:1)
唯一受支持的方法是使用std::memcpy
。将前八个字节复制到一个变量中,然后将其他八个字节复制到第二个变量中。
这可以通过&
运算符的地址和指针算法轻松实现:
std::uint64_t part1, part2;
std::memcpy(&part1, v6Bytes.data(), 8);
std::memcpy(&part2, v6Bytes.data() + 8, 8);
复制相反的方法以将数据返回阵列。
答案 1 :(得分:0)
我认为原始数组是网络字节顺序(bigendian),并执行以下操作:
auto ip = boost::asio::ip::address_v6::from_string("1456:94ce:2567:a4ef:1356:94de:2967:a4e8");
auto v6Bytes = ip.boost::asio::ip::address_v6::to_bytes();
std::uint64_t num1;
std::uint64_t num2;
std::copy(std::begin(v6Bytes), std::begin(v6Bytes) + std::size(v6Bytes) / 2, (unsigned char*)&num1);
std::copy(std::begin(v6Bytes) + std::size(v6Bytes) / 2, std::end(v6Bytes), (unsigned char*)&num2);
// assume network byte order
boost::endian::big_to_native(num1);
boost::endian::big_to_native(num2);
// and back again
std::array<unsigned char, 16> bytes;
boost::endian::native_to_big(num1);
boost::endian::native_to_big(num2);
std::copy((unsigned char*)&num1, ((unsigned char*)&num1) + 8, bytes.data());
std::copy((unsigned char*)&num2, ((unsigned char*)&num2) + 8, bytes.data() + 8);
assert(bytes == v6Bytes);