PIC*_*ain 10 c character long-integer
我有一个32位长的变量CurrentPosition,我想分成4位,8位字符.我如何在C中最有效地做到这一点?我正在使用8位MCU,8051架构.
unsigned long CurrentPosition = 7654321;
unsigned char CP1 = 0;
unsigned char CP2 = 0;
unsigned char CP3 = 0;
unsigned char CP4 = 0;
// What do I do next?
Run Code Online (Sandbox Code Playgroud)
我应该用一个指针引用CurrentPosition的起始地址然后再添加两个地址四次的地址吗?
这是小恩迪安.
我还希望CurrentPosition保持不变.
nos*_*nos 18
CP1 = (CurrentPosition & 0xff000000UL) >> 24;
CP2 = (CurrentPosition & 0x00ff0000UL) >> 16;
CP3 = (CurrentPosition & 0x0000ff00UL) >> 8;
CP4 = (CurrentPosition & 0x000000ffUL) ;
Run Code Online (Sandbox Code Playgroud)
您也可以通过指针访问字节,
unsigned char *p = (unsigned char*)&CurrentPosition;
//use p[0],p[1],p[2],p[3] to access the bytes.
Run Code Online (Sandbox Code Playgroud)
我认为你应该考虑使用一个联盟:
union {
unsigned long position;
unsigned char bytes[4];
} CurrentPosition;
CurrentPosition.position = 7654321;
Run Code Online (Sandbox Code Playgroud)
这些字节现在可以访问为:CurrentPosition.bytes [0],...,CurrentPosition.bytes [3]