Solved

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

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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 …
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
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…

733 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