0

I have a string of ASCII characters. I convert this to hex string using the unpack function.

#! /usr/bin/perl

use strict;
use warnings;

my $str="hello";
my $value=unpack("H*",$str);

print $value,"\n";

**output:** 68656c6c6f

Now, lets say, I want to use this output as a string of hex bytes, read one byte at a time and perform some computation on it and store the output in another variable.

For instance,

#! /usr/bin/perl

use strict;
use warnings;

my $str="hello";
my $value=unpack("H*",$str);

my $num=0x12;
my $i=0;

while($i<length($value))
{
    my $result.=(substr($value,$i,2)^$num);
    $i+=2;
}

print $result,"\n";

**output:**

Argument "6c" isn't numeric in bitwise xor (^) at test.pl line 13.
Argument "6c" isn't numeric in bitwise xor (^) at test.pl line 13.
Argument "6f" isn't numeric in bitwise xor (^) at test.pl line 13.
8683202020

The output is incorrect and also there are several warnings.

If we take the first hex byte of the string, "hello" as an example:

68 xor 12 = 7A

However, the output shows it as 86. The output is incorrect and also I am not sure how it got an output of 86.

What is the right way to do it?

4

1 回答 1

6

如果某些东西是十六进制的,它必然是一个字符串,因为十六进制是一个数字的人类可读表示。你不想要一个字符串;您需要一系列数字,其中每个数字都是字符的数值。您可以使用ord逐个字符获取数字,但unpack也提供了方法:

my @bytes = unpack 'C*', $str;

做你想要的处理:

$_ ^= $num for @bytes;

并重构字符串:

$str = pack 'C*', @bytes;

以上三者结合:

$str = pack 'C*', map $_ ^ $num, unpack 'C*', $str;

你也可以这样做:

my $mask = chr($num) x length($str);
$str ^= $mask;
于 2012-11-08T02:22:03.243 回答