Click here to Skip to main content
15,885,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
c++

C++
typedef unsigned char  U08;
typedef unsigned short U16;
typedef unsigned long  U32;

	U08 cpBuffer[] = {0x03, 0x06, 0x10, 0x02, 0x01, 0x01};	
	U32 BodyLength = 6;

	U16 CheckSum = 0x0000;
	U16 ZeroPadding = 0x0000;
	U16 Temp;
	U16 Test;

	if (!cpBuffer) 
		cout << "0" << endl;
	if (BodyLength < 1) 
		cout << "0" << endl;

	if((BodyLength % 2) != 0) 
	{
		ZeroPadding = (0x00FF & cpBuffer[BodyLength-1]);
		BodyLength--;
	}

	for (U32 i= 0; i < BodyLength; i+=2)
	{
		memcpy(&Temp, &cpBuffer[i], sizeof(U16));

		//cout << "index: " << i << endl;
		//cout << "cpBuffer: " << cpBuffer[i] << endl;
		cout << "Temp: " << Temp << endl;
		
		CheckSum += Temp;
		//cout << "checkSum: " << CheckSum << endl;
	}

	CheckSum += ZeroPadding;

	cout << "checkSum: " << CheckSum << endl;


==================================================================================

How to Python?
Posted
Updated 6-Jan-15 21:00pm
v2
Comments
Sergey Alexandrovich Kryukov 7-Jan-15 2:39am    
There is no strict memory copy in Python, because Python does not work with memory directly. Probably you can get help if you explain the purpose.
—SA
Jochen Arndt 7-Jan-15 3:10am    
There is no need to use memcpy in your C++ example.
You can use this inside the loop and remove the ZeroPadding handling (including decrementing BodyLength when odd):
CheckSum += cpBuffer[i];
if (i < BodyLength -1)
CheckSum += cpBuffer[i+1] << 8;

I don't know much about Python. But it should be possible to implement that in Python.
Member 10193953 7-Jan-15 4:38am    
thank you!!

1 solution

Please note you don't need memcpy, neither in C++ nor in Python, to perform such computations.
See, for instance, this Stack Overflow's question: "checksum udp calculation python"[^] to get some insight on how to use ordinary Python language features to compute checksums.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900