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?
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.
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);
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.
The steps are:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With