Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i convert an unsigned char array into an unsigned long long?

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++?

like image 233
j. doe Avatar asked Jan 14 '16 01:01

j. doe


2 Answers

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.)

like image 142
Keith Thompson Avatar answered Sep 28 '22 03:09

Keith Thompson


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.

like image 30
yngccc Avatar answered Sep 28 '22 03:09

yngccc