Convert bytes in a C array as longs

回眸只為那壹抹淺笑 提交于 2019-12-11 09:31:51

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/11295728/convert-bytes-in-a-c-array-as-longs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!