If I have:
char buffer[16];
How can I convert its raw bytes into a:
boost::multiprecision::uint128_t
?
I tried doing a standard C-style cast:
uint128_t myInt = *(uint128_t*)buffer;
though it doesn't seem to work properly. Also tried using a dynamic_cast
I found this page: https://www.boost.org/doc/libs/1_56_0/libs/multiprecision/doc/html/boost_multiprecision/tut/conversions.html
on how to do conversations, but it doesn't seem to cover this type of thing. Any ideas?
EDIT: One of the comments suggested using memcpy (if it was like GCC's 128 bit uint) to copy the bytes into the uint128_t. That doesn't seem to work properly if done in the way I would expect: Am I missing something?
I found a way to do this that works based off of the dynamic nature of the uint128_t type. It seems to not use all 16 bytes for the numeric value at all times. It only uses them if it thinks they are needed (which is why a primitive memcpy() doesn't work).
So the trick is to force it think all 16 bytes are needed, then memcpy() the data in. We can do that by setting an initial value of -1 (or all Fs):
boost::multiprecision::uint128_t getUintFromBuffer(const std::vector<unsigned char> &buf)
{
boost::multiprecision::uint128_t retU = -1;
memset(&retU, 0, 16);
memcpy(&retU, buf.data(), std::min(buf.size(), (size_t)16));
return retU;
}
int main()
{
std::vector<unsigned char> buf;
buf.resize(16);
buf[0] = 0xaa;
buf[15] = 0xff;
std::cout << std::hex << getUintFromBuffer(buf) << std::endl;
return EXIT_SUCCESS;
}
Running this example prints:
FF0000000000000000000000000000AA
And that is what I was looking for :)