Home: Perl Programming Help: Beginner:
ASCII hex to binary bits

New User

Nov 5, 2012, 11:51 AM

Views: 4368
ASCII hex to binary bits

Hi All,

I need to change some ASCII hex strings to their binary values (stored in a binary file, not ASCII).

I read the ASCII hex from a file a line at a time. The file has each pair of hex values spearated by a space (FE 14 3E etc etc)

foreach my $c1 (split(/(..)\s/, $line) 
my $c2 = pack ('H2', $c1);
print "$c2";

My problem is that $c2 contains a 16 bit value not an 8 bit value. How can I get an 8 bit value?



Nov 5, 2012, 8:22 PM

Views: 4357
Re: [Csmith] ASCII hex to binary bits

I find pack and unpack to be about the hardest perl language feature that there is. I have tried this on perl v8.14.

use strict; 
use warnings;
my $line = "01 23 45 67 89 ab cd ef\n";
my $packed = pack 'H2' x 8, split( / /, $line );
print unpack( 'H*', $packed );

If you are sending the packed string to another computer, you still must worry about the "endian" issues.
Good Luck,

New User

Nov 7, 2012, 9:02 AM

Views: 4351
Re: [BillKSmith] ASCII hex to binary bits

Thanks for the help!

I was using split incorrectly. When I ran it through the Perl debugger I saw that it was getting called twice... hence the 2 bytes instead of one.