tags:

views:

74

answers:

2

I need a small program that can calculate the checksum from a user input.

Unfortunately, all I know about the checksum is that it's xor all data in packet.

I have tried to search the net for an example without any luck.

I know if I have a string: 41,4D,02,41,21,04,02,02,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00

This should result in a checksum of 6A.

Hopefully someone could help me. If someone has an example writen in Python 3, could also work for me

+1  A: 

Here you go:

unsigned char *packet;
unsigned char xor = 0;
for ( int i = 0 ; i < packet_len ; i ++ ) {
   xor = xor ^ packet[i];
}
// xor has the required checksum
adamk
Thanks for the sample. I'll try this
Brian
Could I ask you to fill in the part with a user input? So I can just compile it? I have only used Python 3 before, so I'am quiet new to C++.
Brian
+1  A: 

If i understand "xor all data in packet" correctly, then you should do something like this:

#include <iostream>
#include <vector>

using namespace std;

int main() 
{
  unsigned int data;
  vector< unsigned int > alldata;

  cout << "Enter a byte (in hex format, ie: 3A ) anything else print the checksum of previous input: ";

  while ( true )
  {
    cin >> hex >> data;

    if ( cin.fail() || cin.bad() )
        break;

    alldata.push_back( data );
    cout << "Enter a byte: ";

  }

  unsigned int crc = 0;

  for ( int i = 0; i < alldata.size(); i++ )
      crc ^= alldata[ i ];

  cout << endl << "The checksum is: " << hex << uppercase << crc << endl;

  system( "pause" );

  return 0;

}

The idea is to establish a variable initialized to 0 and then xor all elements of the packet with it while storing the result of the operation in the same variable on each step.

EDIT: edited the answer to provide complete working example (far from perfect, but works). Usage: enter bytes as required, once you are finished with input, enter anything invalid, for examle 'q' (cannot be a hexadecimal number). You will get the checksum printed.

PeterK
Hi PeterKYour example works perfekt for me needsThank you for having taken the time to do this. I appreciate it very much
Brian
@Brian: I'm glad i was able to help you. Please check this as an accepted answer, it is considered polite. Thanks, Peter
PeterK
Hi Peter. I was trying to click on "This answer is useful" but I couldnt, because I dont have 15 reputation. I just missed the other option.
Brian