Peter’s blog ✴ Week 140 ✴ 22 November 2021

THE WEEKLY CHALLENGE
Add and multiply

The Perl Camel

Task 1

Add binary

You are given two binary numbers, $a and $b. Write a script to simulate the addition of the given binary numbers. The script should simulate something like $a + $b. (operator overloading)

Examples


Example 1
Input: $a = 11; $b = 1;
Output: 100

Example 2
Input: $a = 101; $b = 1;
Output: 110

Example 3
Input: $a = 100; $b = 11;
Output: 111

Analysis

My feeling is that the clearest way to do this is to write 2 functions, dec_to_bin() and bin_to_dec(). The challenge can then be addressed with

$result = dec_to_bin(bin_to_dec($a) + bin_to_dec($b));

The 'dec' format is a number stored in Perl's or the underlying machine's native format, and the 'bin' format is a series of 0s and 1s representing the individual binary digits of the number.

The dec_to_bin function is readily available in Perl as
sprintf('%b', $a), but bin_to_dec is a little harder. I had hoped for eval(0b$arg), but sadly that doesn't work.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 111



example: 1

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2021-11-22
# PWC 140 task 1

use v5.20;
use warnings;
use strict;

my (@tests, $a, $b);

# pairs to be added
@tests = (11, 1,   101, 1,   100, 11,   10101, 1010,   0, 111,   1111111111, 1111111111);

while (1) {
    
    # pick off next pair
    $a = shift @tests;
    last unless length($a);
    $b = shift @tests;
    
    # give answer
    say qq[$a + $b = ] . dec_to_bin(bin_to_dec($a) + bin_to_dec($b));
}

sub bin_to_dec {
    
    # converts a string of 0s and 1s to a decimal value
    my ($arg, $result);
    
    $arg = $_[0];
    $result = 0;
    
    # process digits
    while ($arg =~ m|^(.)(.*)$|) {
        $result = 2 * $result + $1;
        $arg = $2;
    }
    return $result;
}

sub dec_to_bin {
    
    # coverts a decimal number to binary representation
    return sprintf('%b', $_[0]);
}

10 lines of code

Output from script

11 + 1 = 100
101 + 1 = 110
100 + 11 = 111
10101 + 1010 = 11111
0 + 111 = 111
1111111111 + 1111111111 = 11111111110

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain