let's say that i have 8 unsigned char, that i want to convert to an unsigned long long.
for example, if all char are equals to 0xFF, the unsigned long long would be equal to 0xFFFFFFFFFFFFFFFF.
what's the most efficient way to do that with C or C++?
For example:
unsigned char buffer[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
unsigned long long target;
memcpy(&target, buffer, sizeof target);
Note that if not all the elements of buffer
have the same value, the result will depend on byte ordering (little-endian vs. big-endian).
This also assumes that unsigned long long
is exactly 8 bytes. That's very commonly true, but it's not guaranteed. (It's also not guaranteed that a byte is exactly 8 bits; it can be more. An unsigned char
is by definition 1 byte.)
Instead of memcpy, you can directly assign the bits
unsigned char buffer[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
unsigned long long l = 0;
for (int i = 0; i < 8; ++i) {
l = l | ((unsigned long long)buffer[i] << (8 * i));
}
I believe this is immune to endianness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With