36

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alisha
  • 1,335
  • 4
  • 13
  • 11
  • 2
    Just one small hint: 1024 in hex is 0x200 while 0xFF is 255 in decimal. –  Aug 30 '13 at 06:59
  • 1
    For the other way around, hexadecimal to decimal, see Stack Overflow question *[How can I convert hex strings into numbers in Perl?](http://stackoverflow.com/questions/1531993)*. – Peter Mortensen Mar 08 '16 at 00:32
  • 1024 = 4 * 256 = 0x400 : `perl -Mbigint -E 'say 1024->as_hex'` prints 0x400 – Tinmarino Dec 09 '18 at 21:26
  • For decimal to octal: *[Perl how can I print a character in octal?](https://stackoverflow.com/questions/18091384/)* (2013). The gist is using `%o` instead of `%X` with sprintf(). But isn't there a more canonical question? – Peter Mortensen Feb 21 '23 at 07:24

4 Answers4

54

1024 in decimal is not 0xFF in hex. Instead, it is 0x400.

You can use sprintf as:

my $hex = sprintf("0x%X", $d);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
codaddict
  • 445,704
  • 82
  • 492
  • 529
30

Caveat: sprintf overflows at 264 ≅ 1019, on 32-bit even already at only 232 ≅ 4×109.

For large numbers, enable the lexical pragma bigint. as_hex is documented in Math::BigInt.

use bigint;
my $n = 2**65;
print $n->as_hex;   # '0x20000000000000000'
daxim
  • 39,270
  • 4
  • 65
  • 132
2

I put these snippets into Perl files in my $PATH:

Convert list of decimal numbers into hexadecimal and binary

for ($i = 0; $i < @ARGV; $i++) {
    printf("%d\t= 0x%x\t= 0b%b\n", $ARGV[$i], $ARGV[$i], $ARGV[$i]);
}

Convert list of hexadecimal numbers into decimal and binary

for ($i = 0; $i < @ARGV; $i++) {
    $val = hex($ARGV[$i]);
    printf("0x%x\t= %d\t= 0b%b\n", $val, $val, $val);
}

Convert list of binary numbers into decimal and hexadecimal

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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CodyChan
  • 1,776
  • 22
  • 35
0

You can use the classical printf().

printf("%x",$d);
tuxuday
  • 2,977
  • 17
  • 18