我知道有很多这样的例子,但没有一个正在发挥作用。 pPtr是指向此类型临时日志的指针
typedef struct
{
TIMESTAMP_TYPE oTimeStamp;
ASSERT_ID_TYPE ucAssertID;
Int16 iData1;
Int16 iData2;
UInt16 uiChecksum;
}
LOG_ENTRY_TYPE;
当我想要存储到EEEPROM时,我将我的日志出列.h oTimestamp的类型为
typedef struct
{
UInt32 ulSecond;
UInt16 usMilliSecond;
UInt16 usPowerCycleCount;
}
TIMESTAMP_TYPE;
所有其他访问和写入工作,即使是毫秒,但我无法将秒时间戳值分解为4个字节。
这是我尝试过的(显然只有一个版本没有注释):
UChar tmpByteHigh;
UChar tmpByteLow;
//Attempt1
tmpByteHigh = (pPtr->oTimeStamp.ulSecond >> 24) & 0x000000FF;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond >> 16) & 0x000000FF;
SPIwrite(tmpByteLow);
tmpByteHigh = (pPtr->oTimeStamp.ulSecond >> 8) & 0x000000FF;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond) & 0x000000FF;
SPIwrite(tmpByteLow);
//Attempt 2
tmpByteHigh = (pPtr->oTimeStamp.ulSecond & 0xFF000000UL) >> 24;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond & 0x00FF0000UL) >> 16;
SPIwrite(tmpByteLow);
tmpByteHigh = (pPtr->oTimeStamp.ulSecond & 0x0000FF00UL) >> 8;
SPIwrite(tmpByteHigh);
tmpByteLow = (pPtr->oTimeStamp.ulSecond) & 0x000000FFUL;
SPIwrite(tmpByteLow);
//Attempt 3
//get msw from 32 bit value and write the 2 msB from it
tmpWord = (pPtr->oTimeStamp.ulSecond >> 16) & 0x0000FFFF;
tmpByteHigh = (tmpWord >> 8) & 0x00FF;
SPIwrite(tmpByteHigh);
tmpByteLow = tmpWord & 0x00FF;
SPIwrite(tmpByteLow);
//get lsw from 32 bit value and write the 2 lsB from it
tmpWord = pPtr->oTimeStamp.ulSecond & 0x0000FFFF;
tmpByteHigh = (tmpWord >> 8) & 0x00FF;
SPIwrite(tmpByteHigh);
tmpByteLow = tmpWord & 0x00FF;
SPIwrite(tmpByteLow);
//Attempt 4
UChar* myPointer = (UChar*)&pPtr->oTimeStamp.ulSecond;
UChar myArray[4];
myArray[0]=myPointer[0];
myArray[1]=myPointer[1];
myArray[2]=myPointer[2];
myArray[3]=myPointer[3];
SPIwrite(myArray[0]);
SPIwrite(myArray[1]);
SPIwrite(myArray[2]);
SPIwrite(myArray[3]);
每次我通过SPI发送0x00 0x00 0x00 0x80。有什么想法吗?对我来说很容易,我不是一个优秀的程序员。
答案 0 :(得分:2)
使用union,您可以通过多种方式访问相同的数据:
typedef union
{
struct {
UInt32 ulSecond;
UInt16 usMilliSecond;
UInt16 usPowerCycleCount;
};
UInt8 byte[8];
}
TIMESTAMP_TYPE;
int main() {
TIMESTAMP_TYPE T;
T.ulSecond = 1;
T.usMilliSecond = 2;
T.usPowerCycleCount = 3;
printf("sizeof(T) = %ld\n", sizeof(T));
for(int i = 0; i < 8; i++)
printf("T[%d] = 0x%2.2X\n", i, T.byte[i]);
return 0;
}
打印:
sizeof(T) = 8
T[0] = 0x01
T[1] = 0x00
T[2] = 0x00
T[3] = 0x00
T[4] = 0x02
T[5] = 0x00
T[6] = 0x03
T[7] = 0x00
请注意,bytes数组具有native endianness。如果这不是所需的字节序,则必须交换字节。