Solved

How to convert a binary file to Hex string? (Perl)

Posted on 2010-08-24
3
672 Views
Last Modified: 2012-05-10
Experts,

how do I convert a binary file to a hex string in Perl?

not-so-working example:

      open(BS_FILE, $bs_file_bin)  or die "can't open $bs_file_bin: $!";
      
      binmode(BS_FILE);
      
      @lines = <BS_FILE>;
      for $line ( @lines ) {
            chomp $line;
         my $int = unpack("N", pack("B32", substr("0" x 32 . $line, -32)));
            my $hex = sprintf("%x", $int );

            print STDOUT "$hex\n";

      }
0
Comment
Question by:php-newbie
3 Comments
 
LVL 10

Accepted Solution

by:
jeromee earned 500 total points
ID: 33516141
I think the issue is that you are mixing <BS_FILE> with binmode.
Try this... it seems to work for me.
use strict;

my $bs_file_bin = "/tmp/bf";

open(BS_FILE, $bs_file_bin)  or die "can't open $bs_file_bin: $!";
binmode(BS_FILE);

my $data;
while( read(BS_FILE, $data, 4) ) {
   my $int = unpack("N", $data);
   my $hex = sprintf("%08X", $int );
   print STDOUT "$hex\n";
}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 33516730
or
perl -lne 'BEGIN{$/=\4}print unpack"H*"' /tmp/bf
0
 

Author Closing Comment

by:php-newbie
ID: 33517034
very awesome!!! Thanks!
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question