I'm not sure what you mean by "all-purpose". Do you want a function that will
convert a decimal number to any base (ie base 2)? If you are just concerned
with decimal to hex, here ya go:
# $dec - decimal number to convert to hex
# $pad - (optional) how long the hex number must be (a minimum). If
# it is not this long, it will be padded with zeros.
# $x - (optional) pass 1 if you want the number to have a '0x' at the
# beginning.
sub toHex
{
my ($dec, $pad, $x) = @_;
my $hex;
my $str = "%";
$str = "0x" . $str if($x);
$str .= "0" . $pad if($pad);
$str .= "x";
$hex = sprintf($str, $dec);
return $hex;
}
my $hex1 = toHex(15, 4, 1);
my $hex2 = toHex(3045);
my $hex3 = toHex(255, undef, 1);
print "$hex1 $hex2 $hex3\n";
Output:
0x000f be5 0xff
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.