【问题标题】:32-bit bitwise Exclusive-OR negation value of a binary packet二进制数据包的 32 位按位异或否定值
【发布时间】:2014-10-05 15:26:07
【问题描述】:

我需要生成一个 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 需求,并发布了一些 C 代码。您希望我们为您编写代码吗?更常见的是,在这个网站上,人们会遇到困难,并提出具体问题,以便我们能够以具体答案作出回应。
  • 好的,很酷。我做了一些编辑。我希望那里的人可以帮助告诉我如何在 erlang 中按位进行xor 否定
  • 我冒昧地回滚到 C++ 代码,因为它与问题高度相关。
  • 如果我用谷歌搜索“xor erlang”和“binary not erlang”,我会得到一些非常好的结果,(我什至不知道关于 erlang 的第一件事!!) 你真正遇到的困难是什么?

标签: c++ c binary erlang


【解决方案1】:

在 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) 调用它。

【讨论】:

    猜你喜欢
    • 2010-09-13
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多