1

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);
2
  • 1
    << works fine with long. In this case, num is always 0, and so you're clearing a to all 0s. Commented Jun 8, 2015 at 23:13
  • 2
    long is not necessarily 64 bits. If you want to make sure, use int64_t from stdint.h. That is the proposed way. Also, make sure the array has the proper byte-order. Commented Jun 8, 2015 at 23:16

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, I was trying to convert an 8-byte char array into a long long and this was the only way to make it happen that I could find.
@DaveCole: I'm happy it helped. Just remember to be careful when shifting signed values. I generally strongly recommend to use unsigned types only for shifting. Also note that long long is not required to have 64 bits and a byte/char (see text) does not need to have 8 bits either. Using the correct types makes your code more self-documenting. Even if that is no production code, you might value that in some years.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.