对数据包中的所有数据进行异或 [英] xor all data in packet

查看:552
本文介绍了对数据包中的所有数据进行异或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个小程序,可以根据用户输入来计算校验和。

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.

我知道我是否有一个字符串: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,00,00

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

这将导致校验和为6A。

This should result in a checksum of 6A.

希望有人能帮助我。如果有人用Python 3编写了示例,也可以为我工作

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;
}

这个想法是建立一个初始化为 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.

编辑:编辑了答案,以提供完整的工作示例(远非完美,但可行)。
用法:输入所需的字节,完成输入后,输入无效的任何内容,例如 q (不能为十六进制数字)。您将得到校验和。

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.

这篇关于对数据包中的所有数据进行异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆