$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | # 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 } |
3 Responses for "Bit Shifting in PowerShell"
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)
Leave a reply