Search code examples
cprintingbyteunsigned-integer

c programming how do i read the bytes stored as little indian?


unsigned short num = 258;

//How can i read the byte value as on how this num 258 is getting store (by default is stored as litle indian right?) so the value should be something like this [ 2, 1 ]or [0x02,0x01] <- as litle endian how do i printf it out?


Solution

  • A pointer to an unsigned char can be used to read the byte representation of an object.

    unsigned char *p = (unsigned char *)&num;
    int i;
    for (i=0; i<sizeof num; i++) {
        printf("%02x ", p[i]);
    }