Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a 48 hex string to bytes using Perl?

Tags:

perl

pack

I have a hex string (length 48 chars) that I want to convert to raw bytes with the pack function in order to put it in a Win32 vector of bytes.

How I can do this with Perl?

like image 399
ron Avatar asked Mar 11 '10 18:03

ron


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

How do you represent a hex in Perl?

The hex function in Perl converts the given hexadecimal number ( of base 16 ) into its equivalent decimal number ( of base 10 ). Returns: equivalent decimal number of the given hexadecimal number.


1 Answers

The steps are:

  1. Extract pairs of hexadecimal characters from the string.
  2. Convert each pair to a decimal number.
  3. Pack the number as a byte.

For example:

use strict;
use warnings;

my $string = 'AA55FF0102040810204080';
my @hex    = ($string =~ /(..)/g);
my @dec    = map { hex($_) } @hex;
my @bytes  = map { pack('C', $_) } @dec;

Or, expressed more compactly:

use strict;
use warnings;

my $string = 'AA55FF0102040810204080';
my @bytes  = map { pack('C', hex($_)) } ($string =~ /(..)/g);
like image 59
Michael Carman Avatar answered Sep 21 '22 17:09

Michael Carman