Independent byte input / output order in c

I need to read 4 byte blocks from input (see below).

#include <stdio.h>
#include <stdlib.h>
unsigned char input[4][8] = {{'A', 'B','C','D','A','B','C','D'},
        {'A', 'B', 'C', 'D','A', 'B', 'C', 'D'},
        {'A', 'B', 'C', 'D','A', 'B', 'C', 'D'},
        {'A', 'B', 'C', 'D','A', 'B', 'C', 'D'}
};
unsigned char output[4][2];
int main(void) {
    int  line_num;
    unsigned int *ptr=(unsigned int*)&input;
    for (line_num=0; line_num < 4*2; line_num++) {
        unsigned char *arr1 = ( (unsigned char*)ptr );
        printf("==> line_num %d: %c%c%c%c\n", line_num, *arr1, *(arr1+1), *(arr1+2), *(arr1+3));
        ptr++;
    }
    return EXIT_SUCCESS;
}

Right now, I'm just using an integer pointer to read 4 bytes and a char * pointer to iterate through 4 byte blocks; This works for a large endian, but will not work for a small endian. Is there a more general and order independent approach to this in "C"?

+4
source share
1 answer

First of all, do not interpret the char buffer in the same way as an unsigned int. You must copy the value to a valid object.

To avoid content issues, determine which order you will use in the transfer, and then the conversion becomes platform independent.

, endian ( ), : ( )

unsigned char data[4] = ... ;

uint32_t value = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);

, .

+2

All Articles