Tuesday, October 12, 2010

Swap Bytes in a Buffer


/**********************************************************************
Description:Swaping of bytes may require while formatting the communication data in some of the systems due to big-endian / little-endian limitations.

This funstion does the swaping of bytes in the supplied buffer and its length.
This code is compiled in C & C++ environments.
***********************************************************************/

void SwapBytes(unsigned char* pBuff, unsigned int uiLength)
{
    if (uiLength == 0 || uiLength == 1)
    {
        return;
    }

    unsigned char* pTemp = pBuff + uiLength - 1;
    unsigned char byteTemp = 0;

    while(pBuff < pTemp)
    {
         byteTemp = *pBuff;
         *pBuff = *pTemp;
         *pTemp = byteTemp;
         pBuff++;
         pTemp--;
    }
}

// usage:
{
unsigned char pBuff[3] = {0x01,0x02,0x03};
SwapBytes(pBuff,3); // becomes {0x03,0x02,0x01};
}


No comments:

Post a Comment