I needed to dome some Bit Shifting in PowerShell but unfortunately PowerShell lacks operator for Bit Shifting. I searched the .NET Framework for anything that allows for bit shifting but was unable to find anything suitable.
I didn't want to revert to C# so I implemented shift left and shift right functions in PowerShell.
The code isn't really pretty and could probably be improved (comments/improvements are welcome!) but here goes (please note that I implemented for bit shifting a byte):
powershell
Download
# convert (possible negative) value to Hex Byte
function valToHexByte([Int16]$val)
{
$s = "{0:x2}" -f $val
$s = "0x" + $s.Substring($s.Length - 2, 2)
return [byte]$s
}
# shift bits left
function shl([int16]$val, [byte]$index=1)
{
$b = valToHexByte $val
$ba1 = New-Object System.Collections.BitArray($b)
$ba2 = New-Object System.Collections.BitArray(8)
for ($i=0 ; $i+$index -lt 8 ; $i++)
{
$ba2.Set($i + $index, $ba1.Get($i))
}
for ($i=0 ; $i -lt $index ; $i++)
{
$ba2.Set($i, 0)
}
$result = New-Object System.Byte[] (1)
$ba2.CopyTo($result, 0)
return $result
}
# shift bits rights
function shr([Int16]$val, [byte]$index=1)
{
$b = valToHexByte $val
$ba1 = New-Object System.Collections.BitArray($b)
$ba2 = New-Object System.Collections.BitArray(8)
for ($i=7-$index ; $i -gt -1 ; $i--)
{
$ba2.Set($i, $ba1.Get($i + $index))
}
for ($i=7 ; $i -gt 7 - $index ; $i--)
{
$ba2.Set($i, $ba2.Get(7))
}
$result = New-Object System.Byte[] (1)
$ba2.CopyTo($result, 0)
return $result
}
I think there may be an easier way to go about this. It's certainly different, if not easier. I've put together a blog post (I've not published it yet, but will do so shortly)
Take a look: http://theessentialexchange.com/blogs/michael/archive/2012/05/10/bit-shifting-in-powershell-redux.aspx
Shifting left = multiply by two (inserts a 0 at the right end);
Shifting right = divide by two (drops the rightmost bit, and inserts a 0 at the left end)
(integer math, no decimals)
(this is ofcourse independent of the dev language used)
@Luc: shift right doesn't insert 0 but inserts 0 or 1 depending on the MSB (shift left always inserts 0)