How do we convert 8 byte char array into long since <<
does not work for type long?
#define word_size 8
long num = 0;
char a[word_size] = "\x88\x99\xaa\x0bb\xcc\xdd\xee\xff";
for (i=0; i < word_size;i++) {
a[(word_size-1) - i] |= (num << (8*(word_size - i - 1))) & 0xFF;
}
printf("%lx\n", num);
The following code is more efficient:
This assumes big endian (highest order byte first) ordering of the bytes in the array. For little endian (as you appear to use) just process it top-down:
Note: whether
char
is signed or unsigned is implementation-dependent, so nail it down to be unsigned, otherwise the logical-or will not work. Better useuint8_t
; that is defined to be 8 bits, whilechar
is not.Note: You should use all-uppercase for constants:
WORD_SIZE
instead ofword_size
. That is a commonly accepted standard (quite the only about case for identifiers in C).