# Perl Weekly Challenge 140: Add Binary

by Abigail ## Challenge

You are given two decimal-coded 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)

### 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


## Discussion

The challenge description is very confusing. What on earth is a decimal-coded binary number? Google doesn't know, and if you search for it, it gives you results for Binary Coded Decimals — which are well known. But it doesn't look like we are dealing with Binary-coded decimals.

Then we are asked to simulate the addtion of binary numbers. Which is a bit confusing. Virtual every general purpuse computer created in the past 70 years does arithmetic using binary. Are we asked to simulate something which is already done? How so? The examples are of no use, what they're showing has as little to do with simulating anything as it as to do with spinach.

Then it mentions "operator overloading" out of the blue. What should we overload? Overload the + operator to do addition instead of, well, uhm, addition?

Gosh, someone really, really ought to proofread those challenges. It won't take more than a few seconds to give this a thumbs down.

As it is often the case, we'll completely ignore the silly instructions and deduce a challenge from the examples. We'll reframe the challenge as:

• You are given two numbers in binary representation.
• Add them, and show the result in a binary representation.

## Solution

The challenge now really boils down to mapping numbers back and forth between an integer and decimal representation. Some languages have support for that, some languages have functions which can be used to do this mapping, and in some languages, we have to roll our own.

In each implementation, we assume the input consists of one or more lines, with two non-negative integers in binary representation on each line. For each line of input, we write a line with the sum of the two numbers to standard output.

### Perl

Perl doesn't have build in function dedicated to mapping numbers from one base to the other, but it does have functions which can be used. To map an integer in binary representation to a regular integer, we prepend the binary number with 0b, and use oct. To get the binary representation of a number, we sprintf with the %b format. This gives us a one-liner: