Converting 8 byte char array into long

前提是你 提交于 2019-12-08 06:56:31

问题


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:


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



来源:https://stackoverflow.com/questions/30720546/converting-8-byte-char-array-into-long

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!