title: Convert a byte stored as string into bits in Perl and modify it
body: <p>I am trying to perform the following using a Perl script:</p>
  
  <ul>
  <li>extract two characters from a hexadecimal number stored as a string --> This will give a byte written as string</li>
  <li>Convert this byte to binary (I must keep leading zeros if they exist)</li>
  <li>change specific bits in the binary </li>
  <li>convert back to hexadecimal</li>
  <li>replace into the original hexadecimal number</li>
  </ul>
  
  <p>To do so, after a long research on the internet, I came up with the following lines:</p>
  
  <pre><code># Initialize my variable: in my function, this is passed as input
  $str = '5B CD 02 01 10';
  
  # Extract the two characters to form a Byte
  $OldByte_str = substr($str,0,2); 
  
  # Convert to binary. Supposed to give '0101 1011'
  $PDM_OldBits =  ( "Binary: %b\n", $PDM_OldByte );
  
  # Replace two bits.Supposed to give '01**10** 1011'
  substr($PDM_OldBit,2,2)= '10';
  
  # Convert back to Bytes. Supposed to give'6B'
  $NewByte_str= sprintf("0x%x", stringdecimal(arraystring($PDM_OldBits))); 
  
  # Substitute back into the original Bytes string.
  # Supposed to give: '**6B** CD 02 01 10'
  substr($str,0,2)= $PDM_NewByte;
  </code></pre>
  
  <p>with:</p>
  
  <pre><code>sub stringdecimal {
      return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  }
  
  sub arraystring {
      my $string = join('', @_);
      return $string;
  }
  </code></pre>
  
  <p>However, the conversion to binary is not taking place; thus i am also not able to check the rest of the code.</p>
  
  <p>As a beginner to Perl, I am asking this question here - in case someone has some hints or solutions to my problem.</p>