πŸ“˜ Converting binary to integer using Perl 6

Convert a binary number to a decimal integer.

Perl is good at its ease of switching between numerical and string representation of the same data. This task is an example where this feature can be used.

The idea is to take a binary number, treat it as a string, prepend the 0bprefix indicating the binary value, and convert the value back to the integer, but a decimal this time. This description is encoded in the following example:

my $bin = '101101';
my $int = "0b$bin".Int;
say $int;

This program prints 45.

It is possible to use an alternative representation of the binary number using a generic form of the value with an explicit radix:

my $bin = '101101';
my $int = ":2<$bin>".Int;
say $int;

As a side note, remember that in Perl 6, you cannot start a numeric literal with 0. For example, the following assignment is incorrect:

my $b = 0110;

This generates a compile-time error, saying that the leading 0 no longer means octal numbers. In Perl 6, all the radix prefixes are unified:Β 0b for binary,Β 0x for hexadecimal, andΒ 0o for octal representation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s