简体   繁体   中英

How can I modify specific part of a binary scalar in Perl?

I adopt select(), sysread(), syswrite() mechanism to handle socket messages where messages are sysread() into $buffer (binary) before they are syswritten.

Now I want to change two bytes of the message, which denote the length of the whole message. At first, I use following code:

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

However, it doesn't work in this way. If the final value of $declen is 85, then the modified $buffer will be "0x35 0x35 0x00 0x02...". I insert digital number to $buffer but finally got ASCII!

I also tried this way:

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

Sadly, this method also failed. The result is such as"0x33 0x 0x00 0x02..." I just wonder why two binary scalar can't be joined into a binary scalar?

Can you help me? Thank you!

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

Untested, but I think this is what you are trying to do... convert a string with two bytes representing a short int into an actual int object and then back again.

我发现了另一种可行的方法-使用vec

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

您不能直接在Perl中加入两个二进制缓冲区,您所要做的就是调用以获取ASCII,然后再对其进行调用并对其进行拆包以取回。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM