将C数组中的字节转换为long

时间:2012-07-02 14:31:46

标签: c arrays arduino

我有一个小端字节顺序的字节数组。如何将其转换为长(四字节)数组?

用外行人的话说,我想合并每四个字节。

1 个答案:

答案 0 :(得分:5)

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];

我赶紧写了一个样本。但是,它没有经过测试。

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;