WDef
Group: Members
Posts: 798
Joined: Sep. 2005 |
|
Posted: Sep. 18 2007,19:57 |
|
A Perl version, since I definitely need the practice:
Code Sample | #!/usr/bin/perl
# # hex2ascikey.pl # Takes hex wifi key as argument and prints asci #
use strict; use warnings;
my $hexkey = shift; chomp $hexkey; $hexkey =~ s/^[+]+//; # or can't cope with a leading + $hexkey =~ s/[:-]//g;
# Insert space every 2 chars $hexkey =~ s/([^\s]{2})/$1 /gs;
my @A = split (/ /, $hexkey);
foreach my $c (@A){ my $dec = hex($c); print chr($dec); }
print "\n"; |
EDIT: Perl version as is can't cope with $ as an illegal input hex char. Gives superior built-in error messaging and tells you that it is ignoring which illegal hex chars.
The bash script runs in around the same time or faster, despite the pipes (subshells), read and 2 sed invocations - not that speed matters here.
Equivalent functionality in bash to both flag and remove illegal hex chars is like:
Code Sample | #!/bin/bash
# # hex2ascikey.sh # Takes hex wifi key as argument and prints asci #
echo -n $1 | sed 's/[0-9A-Fa-f]//g t message :message s/^.\+$/Ignoring non-hex chars &\n/'
echo -n $1 | sed 's/[^0-9A-Fa-f]//g' | while read -n 2 HEXCH; do printf "%s\x$HEXCH" 2>/dev/null; done | sed 's/\\\x$//'
echo
|
which is more sed than I usually care to learn and shows why I like Perl. No doubt this could be made better. To cope with $ as a non-hex input char, bash script argument needs to be put in single quotes.
A more readable alternative bash script might parse the input char by char instead.
|