Split 32-bit into 4 bytes

I know that there are many examples for this, but BELOW they do not work. pPtr is a pointer to a temporary log of this type

typedef struct
{
  TIMESTAMP_TYPE oTimeStamp;
  ASSERT_ID_TYPE ucAssertID;
  Int16 iData1;
  Int16 iData2;
  UInt16 uiChecksum;
} 
LOG_ENTRY_TYPE;

where I delete my log when there is one that I want to save in EEEPROM.
oTimestamp is of type

typedef struct  
{
  UInt32 ulSecond;  
  UInt16 usMilliSecond;
  UInt16 usPowerCycleCount; 

 } 
  TIMESTAMP_TYPE;

All other access and write operations work even in milliseconds, but I can’t get the timestamp value of seconds divided by 4 bytes.

Here is what I tried (obviously with only one version without comments):

 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]);

Every time I get 0x00 0x00 0x00 0x80 sent over SPI. Any suggestions? Be calm, I'm not a big programmer.

+4
source share
1 answer

Use union , and you can access the same data in several ways:

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

, endianness. , .

+2

All Articles