## Bitwise Operations

Continuing our look at binary operations I decided I wanted to be able to perform the bitwise operations – band, bor, bxor and get the results back as binary.  We already have operators for these actions in PowerShell so its just a matter of wrapping the appropriate conversion code around them.  I’ll show the code for band here.  The other two are very similar and will be available in the module when I post it on codeplex.

 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 function Get-BinaryAND { param(     [string]\$inputvalue1,     [string]\$inputvalue2,     [switch]\$showsum )     if (\$inputvalue1.length -ne \$inputvalue2.length){Throw "Input values must be same length"} ## check valid binary numbers ## move this to a validation test     Test-Binary \$inputvalue1     Test-Binary \$inputvalue2     \$res = (ConvertTo-Decimal -inputvalue \$inputvalue1 -binary) `          -band (ConvertTo-Decimal -inputvalue \$inputvalue2 -binary)     \$ans = (ConvertTo-Binary -inputvalue \$res).PadLeft(\$inputvalue1.length, "0")     if (\$showsum) {         \$inputvalue1         \$inputvalue2         "-" * \$inputvalue1.length         \$ans     }     else {         \$ans     } }

Two binary numbers as input as we saw in the addition\subtraction functions.  I have changed the names to be consistent across the module. Perform the standard checks and then convert them to decimal and perform the band. The result is converted back to binary – padding left with zeros if required.

I decided to show the inputs and output if required – may be a good learning tool to understand this.

usage is straight forward

PS> Get-BinaryAND -inputvalue1 1010 -inputvalue2 0011
0010
PS> Get-BinaryAND -inputvalue1 10111010 -inputvalue2 01110011 -showsum
10111010
01110011
--------
00110010

The module contents stand at

ConvertTo-Binary
ConvertTo-Decimal
ConvertTo-Hex
Get-BinaryAND
Get-BinaryDifference
Get-BinaryOR
Get-BinarySum
Get-BinaryXOR
Test-Binary
Test-Hex

I need to add a couple of functions to do hex addition and subtraction and then its done