将8个字节的char数组转换为long

编程入门 行业动态 更新时间:2024-10-24 08:26:52
本文介绍了将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

本文发布于:2023-10-28 08:29:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   字节   long   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!