ðŸ“˜ Presenting integers as binary, octal, and hex using Perl 6

# ðŸ“˜ Presenting integers as binary, octal, and hex using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Print a given integer number in the binary, octal, and hexadecimal representations.

On an integer object, call the basemethod with the corresponding number:

`say 42.base(2); # 101010say 42.base(8);  # 52say 42.base(16); # 2A`

Alternatively, use theÂ `fmt` method, which is defined for integers and accepts the formatting string in theÂ printfformat:

`my \$int = 42;say \$int.fmt('Hex: %x'); # Hex: 2asay \$int.fmt('Oct: %o'); # Oct: 52say \$int.fmt('Bin: %b'); # Bin: 101010`

In Perl 6, there also exists a conventional functionÂ `printf`, which works similarly to how it behaves in other programming languages: It needs a formatting string and a list of values to be substituted to theÂ `%`-placeholders.

`my \$int = 42;printf("Hex: %0x\n", \$int); # Hex: 2aprintf("Oct: %o\n", \$int);  # Oct: 52printf("Bin: %b\n", \$int);  # Bin: 101010`

The above examples print the values without their radix prefixes. To add a prefix, use theÂ `%#` forms:

```printf("Hex: %#x\n", \$int); # Hex: 0x2a
printf("Oct: %#o\n", \$int);Â # Oct: 052 (not 0o52!)
printf("Bin: %#b\n", \$int);Â # Bin: 0b101010```