header image

Binary Subtraction

Posted by: | May 7, 2010 | 2 Comments |

Continuing our look at maths functions in binary (hex is to come) lets have a quick look at subtraction

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
function Get-BinaryDifference {
param(
    [string]$value1,
    [string]$value2
)
## check valid binary numbers
## move this to a validation test
    Test-Binary $value1
    Test-Binary $value2

    $diff = (ConvertTo-Decimal -inputvalue $value1 -binary) `
     (ConvertTo-Decimal -inputvalue $value2 -binary)

    if ($diff -lt 0){Throw "Binary subtraction produces negative number"}
    else {ConvertTo-Binary -inputvalue $diff}
}

 

Always assume that value2 will be subtracted from value1 therefore value2 should be smaller.

The function is the same as the addition except we perform a subtraction 🙂

And we check to see if we have a negative result.  If so throw a wobbly and end the action.

These binary and hex functions will be the next module added to PSAM on codeplex

under: Modules, PowerShellV2

2 Comments

  1. By: ALEXAQ on August 1, 2011 at 3:01 am      

    1000111011101110111011 CONVERT TO DECIMAL !!!

  2. By: RichardSiddaway on August 1, 2011 at 5:16 am      

    I tried
    ConvertTo-Decimal -inputvalue 1000111011101110111011 -binary

    and got 2341819 which is the same answer I got using the Windows calculator

    I don’t understand the comment