CRC16 calculation through Java ?

I am trying to calculate CRC CCITT checksum for given Hex string?

This is how I tried

Code:

`public class CRC16CCITT { `

public static void main(String[] args) {

int crc = 0xFFFF; // initial value

int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)

String str = "0009";

byte []by = str.getBytes();

for (byte b : by) {

for (int i = 0; i < 8; i++) {

boolean bit = ((b >> (7-i) & 1) == 1);

boolean c15 = ((crc >> 15 & 1) == 1);

crc <<= 1;

if (c15 ^ bit) crc ^= polynomial;

}

}

crc &= 0xffff;

System.out.println(crc);

System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));

}

}

-----------------

expected output = 1d06

actual output = cf63

:(doh):

I have tried with many ways but I am not able to make it work.

Can anybody help me in this?

Thanks,

Shrinath

Re: CRC16 calculation through Java ?

Can you show the algorithm, given the input how you would manually create the output?

What are the intermediate values for that should be created?

Re: CRC16 calculation through Java ?

Hi Norm,

I have algorithm which is in C,

Code:

`/** @fn void CRC_calcCrc8(u16 *crcReg, u16 poly, u16 u8Data)`

* @ 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 *crcRegPointer to current CRC register.

* @param poly Polynomial to apply.

* @param u8Datau8 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;

}

}

-------------------

few i/ps and o/ps are

(I/p is hex string)

i/p - "0003" ==> o/p="1D0C"

i/p - "0009" ==> o/p="1D06"

Thanks for your reply, :)

shrinath

Re: CRC16 calculation through Java ?

How will another program in another language help show the intermediate results that should be output by the algorithm so that they can be compared to what the intermediate results are from your program?

I see that the c program has comments describing what it is trying to do.

What happened to those comments when you wrote the java version?