[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Perl Golf, Ethernet to Token Ring MAC Address



Hello All,

Recently I was playing with ethereal (from www.zing.org) and I needed to
convert MAC addresses as seen on a Token Ring into the address they
originally were on an Ethernet segment.  Token Ring's 6 byte MAC address is
big endian, where as Ethernet is read as little endian (or is it the other
way around?).  Hence I need to reverse the bits of each byte to convert from
one to the other. Eg  "123456789abc" in Token ring is represented as
482c6a1e593d on Ethernet. ( "12" in hex is 00010010 in binary, reversed is
01001000 which is "48" in hex, 34 => 2C, etc).
 
I thought this was a suitable candidate for some perl golf. Input and output
is a single 12 character text string matching /^[0-9a-f]{12}$/. Input is via
@ARGV . Output is to STDOUT. The real-world code I used looked (a bit) like
this:

my
%reverse_bits=("0","0","1","8","2","4","3","c","4","2","5","a","6","6","7","
e","8","1","9","9","a","5","b","d","c","3","d","b","e","7","f","f");

print Eth_2_Tok($ARGV[0]);

# Explicit Method
sub Eth_2_Tok { 
 	@nibble_array = split //, $_[0];
 	my $answer;
 	while (@nibble_array) {
 		my $high_nib=shift @nibble_array;
 		my $low_nib=shift @nibble_array;
 		$answer.=$reverse_bits{$low_nib}.$reverse_bits{$high_nib}
 	}
 	return $answer;
 } 

My solutions are written below:

<SPOILER WARNING> 



























I "golf"ed the explicit method down to a disappointing 82 chars using a
regular expression with:

%c=split//,'0018243C425A667E8199A5BDC3DBE7FF';$_=pop;s/(.)(.)/$c{$2}$c{$1}/g
;print

But was amazed that a pack/unpack combination could do better at 61 chars.

for(unpack"B8"x6,pack"H12",pop){print unpack"H*",pack"b8",$_}

Any suggestions/improvements ?



Alistair McGlinchy 

__________________________________________________________________________________________

Registered Office:
Marks and Spencer p.l.c
Michael House, Baker Street,
London, W1U 8EP
Registered No. 214436 in England and Wales.

Telephone  (020) 7935 4422
Facsimile  (020) 7487 2670

www.marksandspencer.com

Please note that electronic mail may be monitored.

This e-mail is confidential. If you received it by mistake, please let us know and then
delete it from your system; you should not copy, disclose, or distribute its contents to
anyone nor act in reliance on this e-mail, as this is prohibited and may be unlawful
_________________________________________________________________________________________

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe