Hi all, I have a need to store a MAC address as an integer in a database. Since a MAC is a 48bit, 3 octet hex, it's not too different from the 32bit, 4 octet decimal of an IP address. There is a lot of code out there for converting IP->Long, but none for MAC->Long. I've darn near got it, but I'm stumped now. Here's what I have:
sub mac2long { my @mac = unpack("A4"x3,shift); my $long = 0; foreach my $octet (@mac) { $long <<= 16; $long |= hex($octet); } $long; } sub long2mac { my $long = shift; my @octets; for (my $i = 2; $i >= 0; $i--) { $octets[$i] = sprintf("%04x",($long & 0xFFFF)); $long >>= 16; } join('.',@octets); } chomp(my $inmac = shift @ARGV); my $long = mac2long($inmac); print "$inmac converted to long: $long\n"; my $outmac = long2mac($long); print "$long converted to mac: $outmac\n";
'Executing mac2int.pl 001095123456' results in:
001095123456 converted to long: 2500998230 2500998230 converted to mac: 0000.9512.3456
For the life of me, I can't figure out why I can't get the last remaining octet back. Anyone have any tips? Justin

In reply to Help with Mac Address to Integer conversion by justintime

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.