Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java CRC 8 for Serial Communication

807591Aug 19 2007 — edited Apr 3 2008
I have found a c function that was written to be used by JNI for serial communication with a device. I am moving away from using the custom native interface and trying to use javax.comm so that I can eventually build a solution that works both in windows and linux.

I have hit a wall with calculating the crc. I have a short[] buffer that I need to send certain parts of that buffer to a function that will calculate the overall crc and place it at the end of the request.

Can oneone convert this following c function into a java method? I have used other java crc examples and have not been able to come up with the same crc that the c function does.
/** @fn void CRC_calcCrc8(u16 *crcReg, u16 poly, u16 u8Data)
  * @brief Standard CRC calculation on an 8-bit piece of data.  To make it
  *					CCITT-16, use poly=0x1021 and an initial crcReg=0xFFFF.
  * 
  * 				Note:  This function allows one to call it repeatedly to continue
  *									calculating a CRC.  Thus, the first time it's called, it
  *									should have an initial crcReg of 0xFFFF, after which it
  *									can be called with its own result.
  *
  * @param *crcReg	Pointer to current CRC register.
  * @param poly			Polynomial to apply.
  * @param u8Data		u8 data to perform CRC on.
  * @return None.
  */
void CRC_calcCrc8(u16 *crcReg, u16 poly, u16 u8Data)
{
	u16 i;
	u16 xorFlag;
	u16 bit;
	u16 dcdBitMask = 0x80;

	for(i=0; i<8; i++)
	{
		// Get the carry bit.  This determines if the polynomial should be xor'd
		//	with the CRC register.
		xorFlag = *crcReg & 0x8000;
		
		// Shift the bits over by one.
		*crcReg <<= 1;
		
		// Shift in the next bit in the data byte
		bit = ((u8Data & dcdBitMask) == dcdBitMask);
		*crcReg |= bit;
		
		// XOR the polynomial
		if(xorFlag)
		{
			*crcReg = *crcReg ^ poly;
		}
		
		// Shift over the dcd mask
		dcdBitMask >>= 1;	
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 1 2008
Added on Aug 19 2007
10 comments
655 views