Skip to content

Instantly share code, notes, and snippets.

@jacoby
Created May 19, 2015 20:45
Show Gist options
  • Save jacoby/0df86b764c7e3093153a to your computer and use it in GitHub Desktop.
Save jacoby/0df86b764c7e3093153a to your computer and use it in GitHub Desktop.
ASCII to binary and vice versa
#!/usr/bin/env perl
use feature qw'say' ;
use strict ;
use warnings ;
use Data::Translate ;
my $data = new Data::Translate;
# allows a2b.pl foobarblee or echo foobarblee | a2b.pl
my @start ;
if ( scalar @ARGV ) {
@start = @ARGV ;
}
else {
while (<STDIN>) { push @start , $_ }
}
say join ' ' ,
map { ( $data->a2b( $_ ) )[ 1 ] }
split m{} ,
join ' ' , @start ;
#space between bytes because that's what the Robot did
#!/usr/bin/env perl
use feature qw'say' ;
use strict ;
use warnings ;
use Data::Translate ;
my $data = new Data::Translate;
my @start ;
if ( scalar @ARGV ) {
@start = @ARGV ;
}
else {
while (<STDIN>) { push @start , $_ }
}
my $start = join ' ' , @start ; # binary octets separated by space chars
for my $l ( split m{\s+} , $start ) {
my ( undef , $o ) = $data->b2a( $l ) ;
# print $o ; # the broken behavior
print $o eq '' ? ' ' : $o ; # knows, if you get '' , you want ' '
}
say '' ;
# https://metacpan.org/source/DAVIEIRA/Data_Translate-0.3/Translate.pm
sub b2a {
shift;
local ($binstr)= @_;
if ($binstr=~/^[01]+$/) {
$as=unpack("A*", pack("B*", $binstr));
return 1,$as;
} else {
return -1,0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment