将8个字节的char数组转换为long [英] Converting 8 byte char array into long

查看:893
本文介绍了将8个字节的char数组转换为long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于<< 对于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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆