Reputation: 43
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?
Upvotes: 0
Views: 649
Reputation: 48605
I would assume the original array is in network byte order (bigendian) and do something like this:
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);
Upvotes: 0
Reputation: 409136
The only supported way is to use std::memcpy
. Copy the first eight bytes into one variable, and then the other eight bytes into the second.
This can easily be accomplished with the address-of &
operator and pointer arithmetic:
std::uint64_t part1, part2;
std::memcpy(&part1, v6Bytes.data(), 8);
std::memcpy(&part2, v6Bytes.data() + 8, 8);
Copy the opposite way for getting the data back into the array.
Upvotes: 1