1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| $somestring = "this is a test";
for ($i = 0; $i <= length($somestring); $i++) {
$arychrs[$i] = dec2hex(ord(substr($somestring, $i, 1)));
}
sub dec2hex {
# parameter passed to
# the subfunction
my $decnum = $_[0];
# the final hex number
my $hexnum;
my $tempval;
while ($decnum != 0) {
# get the remainder (modulus function)
# by dividing by 16
$tempval = $decnum % 16;
# convert to the appropriate letter
# if the value is greater than 9
if ($tempval > 9) {
$tempval = chr($tempval + 55);
}
# 'concatenate' the number to
# what we have so far in what will
# be the final variable
$hexnum = $tempval . $hexnum ;
# new actually divide by 16, and
# keep the integer value of the
# answer
$decnum = int($decnum / 16);
# if we cant divide by 16, this is the
# last step
if ($decnum < 16) {
# convert to letters again..
if ($decnum > 9) {
$decnum = chr($decnum + 55);
}
# add this onto the final answer..
# reset decnum variable to zero so loop
# will exit
$hexnum = $decnum . $hexnum;
$decnum = 0
}
}
return $hexnum;
} # end sub |
Partager