c++、java CRC16算法

c++代码

int get_crc16 (unsigned char *bufData, unsigned int buflen, unsigned char *pcrc)
{
	int ret = 0;
	unsigned short CRC = 0xffff;
	unsigned short POLYNOMIAL = 0xa001;
	int i, j;


	if(bufData == NULL || pcrc == NULL)
	{
		return -1;
	}

	if (buflen == 0)
	{
		return ret;
	}
	for (i = 0; i < buflen; i++)
	{
		CRC ^= bufData[i];
		for (j = 0; j < 8; j++)
		{
			if ((CRC & 0x0001) != 0)
			{
				CRC >>= 1;
				CRC ^= POLYNOMIAL;
			}
			else
			{
				CRC >>= 1;
			}
		}
	}

	
	printf ("CRC=%X\n", CRC);
	pcrc[0] = (unsigned char)(CRC & 0x00ff);
	pcrc[1] = (unsigned char)(CRC >> 8);

	return ret;
}

int main(int argc, char *argv[])
{
	
	unsigned char cc[]={0x30,0x30,0x34,0x36,0x46,0x44,0x36,0x30,0x30,0x30,0x01,0x72,0x65,
		0x66,0x65,0x72,0x69,0x6E,0x66,0x6F,0x2E,0x63,0x73,0x76,0x00,0x00
		,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
		,0x00,0x00,0x00,0x01,0xf4,0x01};
		
	//unsigned char cc[] = {0x00, 0xff};
	unsigned char crcs[3] = {0};
	int ret = get_crc16 (cc, 46, crcs);
	printf("ret = %d\n", ret);
	return 0;
}

java代码

public static int get_crc16 (byte[] bufData, int buflen, byte[] pcrc)
	{
		int ret = 0;
		int CRC = 0x0000ffff;
		int POLYNOMIAL = 0x0000a001;
		int i, j;


		if (buflen == 0)
		{
			return ret;
		}
		for (i = 0; i < buflen; i++)
		{
			CRC ^= ((int)bufData[i] & 0x000000ff);
			for (j = 0; j < 8; j++)
			{
				if ((CRC & 0x00000001) != 0)
				{
					CRC >>= 1;
					CRC ^= POLYNOMIAL;
				}
				else
				{
					CRC >>= 1;
				}
			}
			//System.out.println(Integer.toHexString(CRC));
		}
		
		System.out.println(Integer.toHexString(CRC));
		pcrc[0] = (byte)(CRC & 0x00ff);
		pcrc[1] = (byte)(CRC >> 8);

		return ret;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		byte[] aa = {0x30,0x30,0x34,0x36,0x46,0x44,0x36,0x30,0x30,0x30,0x01,0x72,0x65,
				0x66,0x65,0x72,0x69,0x6E,0x66,0x6F,0x2E,0x63,0x73,0x76,0x00,0x00
				,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
				,0x00,0x00,0x00,0x01,(byte)0xf4,0x01};
		byte[] bb = new byte[3];
		Crc16.get_crc16(aa, aa.length, bb);
		
		System.out.println(Integer.toHexString((int)bb[0] & 0x000000ff));
		System.out.println(Integer.toHexString((int)bb[1] & 0x000000ff));
		

	}

经过验证c++和java计算的结果是一样的。可以放心使用。

c++、java CRC16算法,布布扣,bubuko.com

c++、java CRC16算法

上一篇:C++ 新特性-右值引用


下一篇:HTTP与HTTPS的区别