CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

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


New User

Nov 5, 2012, 11:51 AM

Post #1 of 3 (4378 views)
ASCII hex to binary bits Can't Post

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

Post #2 of 3 (4367 views)
Re: [Csmith] ASCII hex to binary bits [In reply to] Can't Post

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

Post #3 of 3 (4361 views)
Re: [BillKSmith] ASCII hex to binary bits [In reply to] Can't Post

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.


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives