title: Hexadecimal Computations in Perl
body: <p>I have a string of ASCII characters. I convert this to hex string using the unpack function.</p>
  
  <pre><code>#! /usr/bin/perl
  
  use strict;
  use warnings;
  
  my $str="hello";
  my $value=unpack("H*",$str);
  
  print $value,"\n";
  
  **output:** 68656c6c6f
  </code></pre>
  
  <p>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.</p>
  
  <p>For instance,</p>
  
  <pre><code>#! /usr/bin/perl
  
  use strict;
  use warnings;
  
  my $str="hello";
  my $value=unpack("H*",$str);
  
  my $num=0x12;
  my $i=0;
  
  while($i&lt;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
  </code></pre>
  
  <p>The output is incorrect and also there are several warnings.</p>
  
  <p>If we take the first hex byte of the string, "hello" as an example:</p>
  
  <pre><code>68 xor 12 = 7A
  </code></pre>
  
  <p>However, the output shows it as 86. The output is incorrect and also I am not sure how 
  it got an output of 86.</p>
  
  <p>What is the right way to do it?</p>