Reputation: 1385
How can I convert a number, $d = 1024
, in decimal to 0xFF in hex in Perl?
The d
variable needs to be assigned to a different variable and be printed, so for readability I required it to be in hexadecimal format.
Upvotes: 37
Views: 97535
Reputation: 454930
1024
in decimal is not 0xFF
in hex. Instead, it is 0x400
.
You can use sprintf as:
my $hex = sprintf("0x%X", $d);
Upvotes: 56
Reputation: 1865
for ($i = 0; $i < @ARGV; $i++) {
printf("%d\t= 0x%x\t= 0b%b\n", $ARGV[$i], $ARGV[$i], $ARGV[$i]);
}
for ($i = 0; $i < @ARGV; $i++) {
$val = hex($ARGV[$i]);
printf("0x%x\t= %d\t= 0b%b\n", $val, $val, $val);
}
for ($i = 0; $i < @ARGV; $i++) {
# The binary numbers you type must start with '0b'
$val = oct($ARGV[$i]);
printf("0b%b\t= %d\t= 0x%x\n", $val, $val, $val);
}
Upvotes: 2