Overclock.net banner

1 - 2 of 2 Posts

·
Registered
Joined
·
1,267 Posts
Discussion Starter · #1 ·
im new-ish to programming. I've been programming for a little over a year now but I have yet to understand exactly how to load a binary file into a perl script or rather have the perl script read a binary file. For example, I have a file that contains the bits, (no spaces)

01000001 01000010 01000011

in ASCII this is, ABC. How can i have a my script do something like the following? I'm perfectly happy doing this in hex if that's easier. 0x414243

Code:

Code:
if ($bit1 == 1) {
     print "true"; 
} else {
     print "false"; 
}
 

·
Premium Member
Joined
·
8,041 Posts
There's a few ways you could do this:

The first, being my preferred method, is using the split function to turn the string into a single character array and then you can query each character on it's own (arrays will start from zero).

Code:

Code:
#!/usr/bin/perl

my $binary_string = "010000010100001001000011";

my @binary_array = split (//, $binary_string);

if ($binary_array[0] == 1) {
        print "true";
} else {
        print "false";
}
You can also do this with substrings:

Code:

Code:
#!/usr/bin/perl

my $binary_string = "010000010100001001000011";

if (substr($binary_string, 0, 1) == 1) {
        print "true";
} else {
        print "false";
}
It's probably also worth noting that in both of the above examples, we're abusing the loose type system. What I mean by this is it's technically a string comparison so we really should be doing the comparison like this:

Code:

Code:
if ($binary_value eq "0") {
        # do something
}
however is the value is always either 1 or 0, we can get away with a numeric comparison. But it's worth noting this because if you're getting your binary data from an unclean source (eg user input), then you'll need to cleanse it first (eg remove any alpha characters) else your program will crash. Thankfully you can strip out those characters quite easily with some clever regex in the split function in the first code example. Something like /([^0-9]|)/ might do the trick, but I've not tested that code.

Lastly, if you want to get really sophisticated, it might be worth investigating CPAN for some pre-existing modules. Depending on your end goal of this project, you may find some killer modules.
 
1 - 2 of 2 Posts
Top