Firstly when people speak about converting binary into hex they're usually
talking about converting a /representation/ of binary into hex.
You have raw data - actually a Windows executable. For historical reasons
program executables are referred to as binaries - but that doesn't mean you
have to convert from binary to access them.
Secondly reading the whole file into memory might be problematic - particularly
if you may have to deal with a very large file. It's better to read the file
in fixed size chunks - then you can put an upper bound on how much memory
your program uses which doesn't depend on the size of the files you feed
it.
Finally unpack() is useful when working with non-textual data. Here it's
used to turn a 8192 (or less) character string into an 8192 element array
of byte values.
#!/usr/bin/perl -w
use strict;
$| = 1;
my $MAXVALUE = 0x30;
my $file = shift or die "Please name a file\n";
open my $fh, '<', $file or die "Can't open $file ($!)\n";
binmode $fh;
my $buffer;
CHUNK:
for (;;) {
# Read as much as 8k, less if at end of file
my $rc = sysread $fh, $buffer, 8192;
die "Read error\n" unless defined $rc;
# No more bytes?
last CHUNK if $rc == 0;
for my $byte (unpack('C*', $buffer)) {
if ($byte > $MAXVALUE) {
printf("%02x > %02x\n", $byte, $MAXVALUE);
last CHUNK;
}
}
}
close $fh;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.