How do I split up a long value (32 bits) into four char variables (8bits) using C?

后端 未结 6 1903
我寻月下人不归
我寻月下人不归 2020-12-29 11:04

I have a 32 bit long variable, CurrentPosition, that I want to split up into 4, 8bit characters. How would I do that most efficiently in C? I am working with an 8bit MCU, 80

6条回答
  •  半阙折子戏
    2020-12-29 11:22

    If You are using an 8 bit MCU shifting a whole 32 bit variable is a bit of work. In this case it's better to read 4 bytes of CurrentPosition using pointer arithmetic. The cast:

    unsigned char *p = (unsigned char*)&CurrentPosition;
    

    doesn't change the CurrentPosition, but if You try to write to p[0] You will change the least significant byte of the CurrentPosition. If You want a copy do this:

    unsigned char *p = (unsigned char*)&CurrentPosition;
    unsigned char arr[4];
    arr[0] = p[0];
    arr[1] = p[1];
    arr[2] = p[2];
    arr[3] = p[3];
    

    and work with arr. (If you want most significant byte first change the order in those assignments).

    If You prefer 4 variables You can obviously do:

    unsigned char CP1 = p[0];
    unsigned char CP2 = p[1];
    unsigned char CP3 = p[2];
    unsigned char CP4 = p[3];
    

提交回复
热议问题