Solved

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

Posted on 2010-08-24
3
638 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
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…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

758 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now