32位二进制报文的异或反值

32-bit bitwise Exclusive-OR negation value of a binary packet

本文关键字:二进制 报文 32位      更新时间:2023-10-16

我需要生成一个4字节的校验和,它被定义为一些二进制数据的"32位按位异或否定值"。我正在用Erlang为一个计费系统重写某个MML接口的编码/解码部分。

这个函数的C/c++版本如下:

Function: GetChkSum 
Description: 
A 32-bit bitwise Exclusive-OR negation value of "message header 
+ session header + transaction header + operation information". 
Input: 
len indicates the total length of "message header + session header 
+ transaction header + operation information". 
Buf indicates the string consisting of message header, session header, 
transaction header, and operation information. 
Output: res indicates the result of the 32-bit bitwise Exclusive-OR negation 
value

void GetChkSum(Int len, PSTR buf, PSTR res) 
{ 
  memset(res, 0, MSG_CHKSUM_LEN); 
  for(int i=0; i<len; i+=4) 
  { 
    res[0]^=(buf+i)[0]; 
    res[1]^=(buf+i)[1]; 
    res[2]^=(buf+i)[2]; 
    res[3]^=(buf+i)[3]; 
  }; 
  res[0]=~res[0]; 
  res[1]=~res[1]; 
  res[2]=~res[2]; 
  res[3]=~res[3]; 
};

我被要求用Erlang重写这个。我该怎么做呢?

在erlang中执行xor操作并不困难(要使用的操作符是bxor,并且用于整型)。但是要编写任何代码,首先需要定义输入和输出的"格式"。从你的例子我猜它可能是ascii码,存储在二进制,或字符串??

一旦定义了输入类型,就可以使用类型为

的函数对结果求值:
negxor(<<>>,R) -> int_to_your_result_type(bnot(R) band 16#FFFFFFFF);
negxor(<<H:32,Q:binary>>,R) -> negxor(Q,R bxor H).

可以用negxor(your_input_to_binary(Input),0)来命名