- Perl ›
- Numerical value ›
- here
Binary, octal, and hexadecimal numerical representations
I will explain the representation of numerical values in binary, octal, and hexadecimal numbers.
Binary number
You can specify a numerical value in binary by prefixing it with 0b.
my $num_bin = 0b1111;
Octal number
If you add 0 to the beginning, you can specify a numerical value in octal.
my $num_oct = 0777;
Hexadecimal
You can specify a number in hexadecimal by prefixing it with 0x.
my $num_hex = 0xFFFF;
Output decimal, octal, hexadecimal
If you want to output in binary, octal, or hexadecimal, specify the format with printf function and output. You can output in binary with%b, octal with%o, hexadecimal (lowercase) with%x, and hexadecimal (uppercase) with%X.
# Output in binary display with %b
printf("\$num_bin = %b\n", $num_bin);
# Output in octal display with %o
printf("\$num_oct = %o\n", $num_oct);
# Output in hexadecimal with %x (lowercase)
printf("\$num_hex = %x\n", $num_hex);
# Output in hexadecimal with %X (uppercase)
printf("\$num_hex = %X\n", $num_hex);
Example
This is an example using binary, octal, and hexadecimal numbers.
use strict;
use warnings;
# You can specify a numerical value in binary by prefixing it with 0b.
my $num_bin = 0b1111;
# If you add 0 at the beginning, you can specify the numerical value in octal.
my $num_oct = 0777;
# You can specify a number in hexadecimal by prefixing it with 0x.
my $num_hex = 0xFFFF;
# Numeric literals expressed in binary, octal, and hexadecimal numbers become decimal when printed.
print "(1) Decimal value\n";
print "\$num_bin = $num_bin\n";
print "\$num_oct = $num_oct\n";
print "\$num_hex = $num_hex\n";
print "\n";
print "(2) Output in each base\n";
# Output in binary display with %b
printf("\$num_bin = %b\n", $num_bin);
# Output in octal display with %o
printf("\$num_oct = %o\n", $num_oct);
# Output in hexadecimal with %x (lowercase)
printf("\$num_hex = %x\n", $num_hex);
# Output in hexadecimal with %X (uppercase)
printf("\$num_hex = %X\n", $num_hex);
Perl ABC