Reputation: 3512
Shift left (-shl
) and shift right (-shr
) operators are only available with PowerShell 3.0 and higher.
How can I shift in PowerShell 2.0?
This is what I have so far. Is there a better way?
>>>$x = 1
>>>$shift = 3
>>>$x * [math]::pow(2, $shift)
8
>>>$x = 32
>>>$shift = -3
>>>$x * [math]::pow(2, $shift)
4
Upvotes: 2
Views: 5094
Reputation: 3485
I stumbled upon the same problem, and I'd like to include some useful information:
PoSh2.0-BitShifting creates a $Global:Bitwise
object that provides most of the bitwise operations.
Example of use (from its own readme):
PS C:\> Enable-BitShift
PS C:\> $Bitwise
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PoShBitwiseBuilder System.Object
PS C:\> $Bitwise::Lsh(32,2)
128
PS C:\> $Bitwise::Rsh(128,2)
32
Upvotes: 1
Reputation: 174900
Unfortunately you can't implement new operators in PowerShell (afaik), but you could wrap the operation inside a function:
function bitshift {
param(
[Parameter(Mandatory,Position=0)]
[int]$x,
[Parameter(ParameterSetName='Left')]
[ValidateRange(0,[int]::MaxValue)]
[int]$Left,
[Parameter(ParameterSetName='Right')]
[ValidateRange(0,[int]::MaxValue)]
[int]$Right
)
$shift = if($PSCmdlet.ParameterSetName -eq 'Left')
{
$Left
}
else
{
-$Right
}
return [math]::Floor($x * [math]::Pow(2,$shift))
}
That makes use a little more readable:
PS> bitshift 32 -right 3
4
PS> bitshift 1 -left 3
8
Upvotes: 3