cn先飞
2021-03-24 14:13
采纳率: 50%
浏览 64

unsigned char 数组如何转换为long long数组

将char 数组转换为long long数组 转换后如图所示

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • qiao_xl 2021-03-24 17:56
    已采纳
    unsigned char a[] = {
    
        0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
    
    
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 
    
    
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 
    
    
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, };
    
        long long llong[4] = {0};
    
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                llong[i] |= (long long)a[j]<<(8*j);
            }
        }

    楼上也可以,这是常规做法

    已采纳该答案
    评论
    解决 1 无用
    打赏 举报
  • ProfSnail 2021-03-24 14:38

    可以使用循环左移的方法,每次左移8位,并用位或方法与char的数值进行拼接。

    评论
    解决 1 无用
    打赏 举报
  • 猫叔压力大 2021-03-24 14:40
    unsigned char a[] = {0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
    							0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, };
    
    long long* pLong = (long long*)a;
    long long llong[4];
    memcpy(&llong, pLong, sizeof(llong));

    内存是连续的,用指针处理一下。

    如果解决了你的问题,顺手点个采纳吧。

    评论
    解决 1 无用
    打赏 举报
  • qiao_xl 2021-03-25 10:04
        unsigned char a[] = {
    
        0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x13,
    
    
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x14, 
    
    
    	0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x15, 
    
    
    	0x10, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x16, };
    
        long long llong[4] = {0};
    
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                llong[i] |= (long long)a[j + 8 * i] << (56 - 8 * j);
            }
        }

    不好意思,昨天发急了没检查,有点毛病,缺了个位移;

    端序也改过来了。

    顺便把反转的也提上来吧。

        long long llong[4] = {0x1212121212121212, 0x1212121212121212,
                              0x1212121212121212, 0x1212121212121212};
        char ch[32];
    
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                ch[j + 8 * i] = llong[i] >> (56 - 8 * j);
            }
        }
    评论
    解决 1 无用
    打赏 举报

相关推荐 更多相似问题