This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Access bytes of a long

Does the C51 compiler provide a way to access the individual bytes of a long value? I can shift bits around to achieve this if I have to, but I'm looking for something faster and more efficient.

  • A common idiom that is not sanctioned by the language standard is to use a union with one member being 'unsigned long' and another member being a 4-element array of 'unsigned char'.

  • b0 = ((unsigned char*)&u32)[0];
    b1 = ((unsigned char*)&u32)[1];
    b2 = ((unsigned char*)&u32)[2];
    b3 = ((unsigned char*)&u32)[3];
    

    A problem with the above is that it gives differnt results for little-endian and big-endian machines.

    A good compiler can sometimes detect the intention behind shift and mask operations, i.e.:

    b0 = (unsigned char)(u32 & 0xff);
    b1 = (unsigned char)((u32 >> 8) & 0xff);
    b2 = (unsigned char)((u32 >> 16) & 0xff);
    b3 = (unsigned char)((u32 >> 24) & 0xff);
    

  • b0 = ((unsigned char*)&u32)[0];
    b1 = ((unsigned char*)&u32)[1];
    b2 = ((unsigned char*)&u32)[2];
    b3 = ((unsigned char*)&u32)[3];
    

    A problem with the above is that it gives differnt results for little-endian and big-endian machines.

    A good compiler can sometimes detect the intention behind shift and mask operations, i.e.:

    b0 = (unsigned char)(u32 & 0xff);
    b1 = (unsigned char)((u32 >> 8) & 0xff);
    b2 = (unsigned char)((u32 >> 16) & 0xff);
    b3 = (unsigned char)((u32 >> 24) & 0xff);