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
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))
A quick check on the result
PS> Convert-ToDecimal -inputvalue $c -binary
That works OK but its a bit messy – too much typing. So I wrote Get-BinarySum
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.