字节转换在C数组作为多头 [英] Convert bytes in a C array as longs

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

问题描述

我在小尾数字节顺序的字节数组。我该如何将它转换为长(四字节)阵列?

在通俗地说,我想每四个字节合并。


解决方案

  BYTE B [4]; //包含字节
INT X = 0;X =(X LT;&下; 8)+ B [3];
X =(X LT;&下; 8)+ B [2];
X =(X LT;&下; 8)+ B [1];
X =(X LT;&下; 8)+ B [0];

我赶紧写了一个样本。这不是测试,但。

  unsigned char型B〔35〕;INT sizeOfB = sizeof的B /的sizeof(无符号字符);INT sizeOfL = sizeOfB / 4;
如果(sizeOfB%4!= 0)++ sizeOfL;
    INT lcount = 0;*长L =新长[sizeOfL]的for(int i = 0; I< sizeOfB; I + = 4){
    长currentLong = 0;    如果第(i + 3'; sizeOfB)
        currentLong =(currentLong&所述;&下; 8)+ B [i + 3中];
    如果第(i + 2'; sizeOfB)
        currentLong =(currentLong&所述;&下; 8)+ B第[i + 2];
    如果第(i + 1&下; sizeOfB)
        currentLong =(currentLong&所述;&下; 8)+ B第[i + 1];    currentLong =(currentLong&所述;&下; 8)+ B第[i + 0];    L [lcount] = currentlong;
    lcount ++;
}//使用规则l ...
删除升;

I have a byte array in little endian byte order. How do I convert it to a long (four bytes) array?

In layman's terms, I want to merge every four bytes.

解决方案

byte b[4];  // Contains bytes
int x= 0;

x= (x << 8) + b[3];
x= (x << 8) + b[2];
x= (x << 8) + b[1];
x= (x << 8) + b[0];

I quickly wrote a sample. It's not tested, though.

unsigned char b[35];

int sizeOfB = sizeof b / sizeof(unsigned char);

int sizeOfL = sizeOfB / 4;
if(sizeOfB % 4 != 0) ++sizeOfL;
    int lcount=0;

long* l = new long[sizeOfL];

for(int i = 0; i < sizeOfB; i+=4){
    long currentLong = 0;

    if(i + 3 < sizeOfB)
        currentLong = (currentLong << 8) + b[i+3];
    if(i + 2 < sizeOfB)
        currentLong = (currentLong << 8) + b[i+2];
    if(i + 1 < sizeOfB)
        currentLong = (currentLong << 8) + b[i+1];

    currentLong = (currentLong << 8) + b[i+0];

    l[lcount]=currentlong;
    lcount++;
}

// Use l...
delete l;

这篇关于字节转换在C数组作为多头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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