danijar
danijar

Reputation: 34185

How to append byte data in C++?

How to append the eight values of a byte array uint8_t[8] into one variable uint64_t?

 uint8_t array[8] = { 0xe4, 0x52, 0xcb, 0xbe, 0xa4, 0x63, 0x95, 0x8f };

 uint64_t result = 0;
 for(int i = 0; i < sizeof(array); ++i)
 {
     // what to do here?
 }

In the example above, result should end up with the value 0xe452cbbea463958f. I am looking for a general solution that is not bound to exactly eight elements from the array.

Upvotes: 1

Views: 7125

Answers (2)

slashingweapon
slashingweapon

Reputation: 11307

If you just want to copy the bytes in order, the best way is to use memcpy:

memcpy(&result, array, sizeof(array));

But if you want to interpret the bytes as being part of a larger number, and treat them as if they were in big-endian order, you have to use the loop that H2CO3 provided:

result = 0;
for (int i=0; i<sizeof(array); i++) {
    result <<= 8;
    result |= array[i];
}

If you want to be able to use the same variable as either a byte array of a 64-bit integer, you could simply typecast. Or if you're writing in C you could use a union.

union myBigInt {
    uint8_t asBytes[8];
    uint64_t asLongInt;
};

Upvotes: 3

user529758
user529758

Reputation:

This is how:

result <<= 8;
result |= array[i];

The |= operator means "assignment after bitwise OR". After result is shifted to the left by 8 places (what <<= does), the new byte is inserted to its end.

Upvotes: 3

Related Questions