【问题标题】:How can I modify specific part of a binary scalar in Perl?如何在 Perl 中修改二进制标量的特定部分?
【发布时间】:2010-10-12 20:34:03
【问题描述】:

我采用 select(), sysread(), syswrite() 机制来处理套接字消息,其中消息在 syswrite 之前被 sysread() 放入 $buffer(二进制)。

现在我想更改消息的两个字节,它们表示整个消息的长度。首先,我使用以下代码:

my $msglen=substr($buffer,0,2); # Get the first two bytes
my $declen=hex($msglen);
$declen += 3;
substr($buffer,0,2,$declen); # change the length

但是,它不能以这种方式工作。如果 $declen 的最终值为 85,那么修改后的 $buffer 将为“0x35 0x35 0x00 0x02...”。我将数字插入到 $buffer 中,但最终得到了 ASCII!

我也试过这种方式:

my $msglen=substr($buffer,0,2); # Get the first two bytes,binary
$msglen += 0b11; # Or $msglen += 3;
my $msgbody=substr($buffer,2); # Get the rest part of message, binary
$buffer=join("", $msglen, $msgbody); 

遗憾的是,这种方法也失败了。结果如“0x33 0x 0x00 0x02...” 我只是想知道为什么两个二进制标量不能合并成一个二进制标量?

你能帮帮我吗?谢谢!

【问题讨论】:

    标签: perl string binary


    【解决方案1】:
    my $msglen=substr($buffer,0,2); # Get the first two bytes
    my $number = unpack("S",$msglen);
    $number += 3;
    my $number_bin = pack("S",$number);
    substr($buffer,0,2,$number_bin); # change the length
    

    未经测试,但我认为这是您正在尝试做的...将具有两个字节表示短 int 的字符串转换为实际的 int 对象,然后再返回。

    【讨论】:

    • 你是对的!我已经为这个问题困扰了很多天!非常感谢!
    【解决方案2】:

    我找到了另一种可行的方法——使用 vec

    vec($buffer, 0, 16) += 3;
    

    【讨论】:

      【解决方案3】:

      您不能直接在 Perl 中加入两个二进制缓冲区,您只需调用 pack 获取 ASCII,然后加入它并调用 unpack 以返回。

      【讨论】:

      • 加入二进制字符串没有问题,但你必须加入正确的数据。
      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2019-12-20
      • 2011-03-13
      相关资源
      最近更新 更多