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

后端 未结 6 1895
我寻月下人不归
我寻月下人不归 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条回答
  •  -上瘾入骨i
    2020-12-29 11:30

        CP1 = (CurrentPosition & 0xff000000UL) >> 24;
        CP2 = (CurrentPosition & 0x00ff0000UL) >> 16;
        CP3 = (CurrentPosition & 0x0000ff00UL) >>  8;
        CP4 = (CurrentPosition & 0x000000ffUL)      ;
    

    You could access the bytes through a pointer as well,

    unsigned char *p = (unsigned char*)&CurrentPosition;
    //use p[0],p[1],p[2],p[3] to access the bytes.
    

提交回复
热议问题