左移(-shl
)和右移(-shr
)運算符僅在PowerShell 3.0及更高版本中可用。PowerShell 2.0中的位移
我該如何轉移PowerShell 2.0?
這是我到目前爲止。有沒有更好的辦法?
>>>$x = 1
>>>$shift = 3
>>>$x * [math]::pow(2, $shift)
8
>>>$x = 32
>>>$shift = -3
>>>$x * [math]::pow(2, $shift)
4
左移(-shl
)和右移(-shr
)運算符僅在PowerShell 3.0及更高版本中可用。PowerShell 2.0中的位移
我該如何轉移PowerShell 2.0?
這是我到目前爲止。有沒有更好的辦法?
>>>$x = 1
>>>$shift = 3
>>>$x * [math]::pow(2, $shift)
8
>>>$x = 32
>>>$shift = -3
>>>$x * [math]::pow(2, $shift)
4
可惜你不能在PowerShell中(據我所知)實施新的運營商,但你可以換一個函數內部操作:
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))
}
,使得使用多一點的可讀性:
PS> bitshift 32 -right 3
4
PS> bitshift 1 -left 3
8
這會失敗,像'bitshift 0xFFFF -right 1'這樣的參數。它返回32767.5而不是32767.將返回值轉換爲[int]將解決該問題。如果OP想用64位數字,如果右移53或更多,將會發生精度損失。這種方法很難修正,因爲[math] :: pow只接受具有52位精度的[double]參數。 –
@ user2460798良好的捕獲,更新的答案樣本(我已經發布了它,相反,任何十進制值都是應該已經移開的位) –
如果數字爲負數,地板將不起作用:'bitshift -1 - 右-1'給出-1。結果朝向負無窮大,而轉換爲[int]趨向於零 –
我偶然發現了同樣的問題,我想包括一些有用的信息:
PoSh2.0-BitShifting創建一個$Global:Bitwise
對象,該對象提供大部分按位操作。使用(從自己的自述)的
例子:
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
這取決於你所說的「更好」 –
清潔,更高效的意思。 '1 << 3'會膨脹,但這是不可能的。 – mcu
我會說最簡潔的方法是升級PowerShell。所有支持的Windows版本至少可以運行PowerShell v3。 –