Converting 8 byte char array into long

3.1k Views Asked by At

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);
1

There are 1 best solutions below

2
On BEST ANSWER

The following code is more efficient:

unsigned char[word_size] = ...;
int64_t num = 0;
for ( int i = 0 ; i < sizeof(a) ; i++ )
    num = (num << 8) | a[i];

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:

for ( int i = sizeof(a) ; --i >= 0 ; )

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 use uint8_t; that is defined to be 8 bits, while char is not.

Note: You should use all-uppercase for constants: WORD_SIZE instead of word_size. That is a commonly accepted standard (quite the only about case for identifiers in C).