//******************************************************************************
//
// CRC5() - Computes a USB CRC5 value given an input value.
//          Ported from the Perl routine from the USB white paper entitled
//          "CYCLIC REDUNDANCY CHECKS IN USB"
//          www.usb.org/developers/whitepapers/crcdes.pdf
//
//          Ported by Ron Hemphill 01/20/06.
//
//  dwinput:    The input value.
//  iBitcnt:    The number of bits represented in dwInput.
//
//  Returns:    The computed CRC5 value.
//
//  Examples (from the white paper):
//      dwInput     iBitcnt     Returns:
//      0x547       11          0x17
//      0x2e5       11          0x1C
//      0x072       11          0x0E
//      0x400       11          0x17
//
//******************************************************************************
#define INT_SIZE    32      // Assumes 32-bit integer size
unsigned CRC5(unsigned dwInput, int iBitcnt)
{
    const U32 poly5 = (0x05 << (INT_SIZE-5));
    U32 crc5  = (0x1f << (INT_SIZE-5));
    U32 udata = (dwInput << (INT_SIZE-iBitcnt));

    if ( (iBitcnt<1) || (iBitcnt>INT_SIZE) )    // Validate iBitcnt
        return 0xffffffff;

    while (iBitcnt--)
    {
        if ( (udata ^ crc5) & (0x1<<(INT_SIZE-1)) ) // bit4 != bit4?
        {
            crc5 <<= 1;
            crc5 ^= poly5;
        }
        else
            crc5 <<= 1;

        udata <<= 1;
    }

    // Shift back into position
    crc5 >>= (INT_SIZE-5);

    // Invert contents to generate crc field
    crc5 ^= 0x1f;

    return crc5;
} //CRC5()