Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2010-08-24
3
Medium Priority
?
747 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 10

Accepted Solution

by:
jeromee earned 2000 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

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 …
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
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…
Six Sigma Control Plans

721 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