我需要生成一个 4 字节校验和,它被定义为某些二进制数据的“32 位按位异或否定值”。我正在为 Erlang 中的计费系统重写某个 MML 接口(interface)的编码/解码部分。
此类函数的 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中进行异或操作没有困难(使用的运算符是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)
调用它。
关于c++ - 二进制数据包的 32 位逐位异或非值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266345/