Pieter Verschaffelt Pieter Verschaffelt - 1 month ago 22
C Question

Copy lowest bytes of an unsigned long long to array in C

I'm trying to use some sort of variable length integers for compression purposes in a project. Now I have a function that calculates what the actual length of an unsigned long long in bytes is (thus how many bytes should be used to correctly display it). I wan't to copy the part of the unsigned long long that's being filled in to an array (so for example I want to copy the 10110010 byte from the long long 0000 ... 0000 10110010). I've tried memcpy, but this does not seem to work. How can I do this?

This is my code so far:

if (list_length(input) >= 1) {
unsigned long long previous = list_get(input, 0);
unsigned long long temp;
for (unsigned int i = 1; i < list_length(input); i++) {
temp = list_get(input, i);
unsigned long long value = temp - previous;
size = delta_get_byte_size(value);
memcpy(&output[currentByte], &value, size);
currentByte += size;
previous = temp;
}
}


I think the issue comes from the fact that the order of individual bytes is not specified in C (little- or big-endian), but I can't seem to find a solution for this problem.

Answer

To do it portably, use shift. To decompose the number into bytes, shift right. To recompose the number from bytes, use shift left. E.g.:

a[0] = x;
a[1] = x >> 8;
a[2] = x >> 16;
a[3] = x >> 24;
a[4] = x >> 32;

x = a[0];
x += (unsigned)a[1] << 8;
x += (unsigned long)a[2] << 16;
x += (unsigned long)a[3] << 24;
x += (unsigned long long)a[4] << 32;