I'm writing to some serial comm port with specific bytes set into buffer. My protocol for write buffer is written below. Platform is Windows and IDE is Visual C++.
- Byte 0 will have message type indicator (Byte)
- Byte 1-4 will have message number (Uint32)
- Byte 5-8 will have unix epoch time (Uint32)
- Byte 13-14 will have number of sample packets (Uint16)
- Bytes 15+ (upto 60) will have sample data packets (Uint16)
- Byte 15+(No of samples*2) will have end of message (Byte)
Now I'm concern about buffer building (raw Bytes) from integer or short values.
void ConvertIntToByte(int iValue, BYTE* ucRawBuffer, int iOffset) { ucRawBuffer[iOffset] = ((iValue >> 24) & 0xFF); ucRawBuffer[iOffset+1] = ((iValue >> 16) & 0xFF); ucRawBuffer[iOffset+2] = ((iValue >> 8) & 0xFF); ucRawBuffer[iOffset+3] = (iValue & 0xFF); } void ConvertShortToByte(short iValue, BYTE* ucRawBuffer, int iOffset) { ucRawBuffer[iOffset] = (iValue >> 8) & 0xFF; ucRawBuffer[iOffset+1] = iValue & 0xFF; } void DataThreadFunction() { while(!m_bClosed) { DWORD dwRet = WaitForSingleObject(m_hDataSendEvent, INFINITE); if(dwRet == WAIT_OBJECT_0) { ResetEvent(m_hDataSendEvent); int iUTCTime = GetEpochTime(); m_iMsgSequence++; ASSERT(m_iMaxSamples != 0); BYTE ucXmtdat[60] = {0}; ucXmtdat[0] = 0x0B; ConvertIntToByte(iUTCTime, ucXmtdat, 1); ConvertIntToByte(m_iMsgSequence, ucXmtdat, 5); ConvertIntToByte(m_iMaxSamples, ucXmtdat, 13); int iOffset = 15; // m_data - member vector populating from some other method for(unsigned int i = 0; i < m_data.size(); i++) { short iCurrData = m_data[i]; ConvertShortToByte(iCurrData, ucXmtdat, iOffset); iOffset += sizeof(unsigned short); } m_data.clear(); iOffset = 15+(m_iMaxSamples*2); ucXmtdat[iOffset] = 0xCA; bool bSuccess = m_objComm.WriteCommPort(ucXmtdat, 60); } } }