Hi,

I'm a newcomer to Perl. Don't know why it took me so long. I've been having a blast writing various scripts to ease my life as a sysadmin.

I'm working on a script to cat log files for a hex address. In our system it is in decimal format. So I would like to take 00910855 and convert it to hex. That part is easy; $hexval = sprintf("%x", $decval);. Being new to perl, I'm a little lost on what functions/process I would use to represent this hex in 00:5B:08:37 value. If I thought about it long enough I imagine I could take the sub string of 2 convert each set to hex val and build the formated string. But I just know this is an old topic and there is a fast better way. Your help would be greatly appreciated. Thanks

tonydm

Recommended Answers

All 4 Replies

"pack" and "unpack" have lots of templates used for this type of conversion of one thing into another thing. I don't know if they can do what you want, but that is a starting place anyway.

Took a look at pack/unpack. Not obvious to me a method to do what I need. So made my own. Again, I am still a pampers wearer with perl. I may be missing a gocha. If so, please let me know. Thanks.

../partial/..
my $macaddr = &dec2mac('00910855');
exit;

sub dec2mac {
my ($dec) = @_;
my $mac = sprintf("%08X", $dec);  #pad with zeros
my $s1 = substr($mac, 0, 2); 
my $s2 = substr($mac, 2, 2);
my $s3 = substr($mac, 4, 2);
my $s4 = substr($mac, 6, 2);
$mac = sprintf("%s:%s:%s:%s", $s1, $s2, $s3, $s4);
return $mac;
}

result is 00:0D:E6:07

sub dec2mac {
    return sprintf("%s:%s:%s:%s",unpack("A2A2A2A2",sprintf("%08X", $_[0])));
}

Thanks KevinADC,

I guess I didn't look close enough at the unpack/pack info. Thanks again for the shortcut. I'll spend some more time looking at your suggestion.

tonydm

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.