Categories

Binary Subtraction

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

2 Responses to Binary Subtraction

  • ALEXAQ says:

    1000111011101110111011 CONVERT TO DECIMAL !!!

  • RichardSiddaway says:

    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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>