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

Published Fri, May 7 2010 21:37 by RichardSiddaway
Filed under: ,

Comments

# re: Binary Subtraction

1000111011101110111011 CONVERT TO DECIMAL !!!

Monday, August 01, 2011 3:01 AM by ALEXAQ

# re: Binary Subtraction

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

Monday, August 01, 2011 5:16 AM by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: