开发者

xor all data in packet

开发者 https://www.devze.com 2023-01-06 11:01 出处:网络
I need a small program that can calculate the checksum from a user input. Unfortunate开发者_运维知识库ly, all I know about the checksum is that it\'s xor all data in packet.

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

Unfortunate开发者_运维知识库ly, 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


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 example q (cannot be a hexadecimal number). You will get the checksum printed.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消