We recently looked at converting numbers to binary and hex.  I then thought that I sometimes need to perform simple arithmetic in these bases so – binary addition.

We can use the functions we already have.  Convert a couple of numbers to binary

PS> \$a = Convert-ToBinary -inputvalue 51
PS> \$b = Convert-ToBinary -inputvalue 39
PS> \$a
110011
PS> \$b
100111

sum them by converting the binary back to decimal, performing the sum and converting back to binary.

PS> \$c = Convert-ToBinary -inputvalue ((Convert-ToDecimal -inputvalue \$a -binary) + (Convert-ToDecimal -inputvalue \$b -binary))
PS> \$c
1011010

A quick check on the result

PS> Convert-ToDecimal -inputvalue \$c -binary
90

That works OK  but its a bit messy – too much typing. So I wrote Get-BinarySum

 001 002 003 004 005 006 007 008 009 010 011 012 013 014 function Get-BinarySum { param(     [string]\$value1,     [string]\$value2 ) ## check valid binary numbers ## move this to a validation test Test-Binary \$value1 Test-Binary \$value2 \$sum = (Convert-ToDecimal -inputvalue \$value1 -binary) + (Convert-ToDecimal -inputvalue \$value2 -binary) Convert-ToBinary -inputvalue \$sum }

Get the two binary numbers – test that they are binary.  Test-Binary is a helper function created from the code used in Convert-ToDecimal

The sum is performed by converting each binary to a decimal, summing them and converting the result back to a binary.

Bingo.  This forms the framework for other functions.