由于<< 对于long类型不起作用,我们如何将8字节char数组转换为long?
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);推荐答案
以下代码更有效:
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 ; )注意:是否 char 是签名的还是未签名的取决于实现,因此请将其固定为未签名,否则逻辑或将不起作用。最好使用 uint8_t ;定义为8位,而 char 不是 。
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.
注意:您应该使用全大写形式的常量: WORD_SIZE 而不是 word_size 。这是一个普遍接受的标准(在C语言中,唯一的情况就是标识符)。
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).
更多推荐
将8个字节的char数组转换为long
发布评论