A function to convert a decimal value to a hex string.
################################################################
# dec2hex
# Convert dec number into hex string
###############################################################
sub dec2hex() {
my $dec = shift();
my $fill = shift(); my $fmt_string; if (defined($fill)){
$fmt_string = "%0" . $fill . "X";
} else {
$fmt_string = "%02X";
}
return sprintf($fmt_string, $dec );
}
Use it as follows:
my $value = 10;
my $hex_string = dec2hex($value);
print "The decimal value $value is written like 0x$hex_string\n";
my $hex_string_long = dec2hex($value, 8);
print "The hex string can be extended with zeros: $hex_string_long\n";