xor all data in packet

﹥>﹥吖頭↗ 提交于 2019-12-22 11:11:02

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3215221/xor-all-data-in-packet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!