Skip to content

Instantly share code, notes, and snippets.

@HarmJ0y
Last active August 31, 2022 17:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HarmJ0y/245eccd0f5ef7e08d7981b9c14ed7738 to your computer and use it in GitHub Desktop.
Save HarmJ0y/245eccd0f5ef7e08d7981b9c14ed7738 to your computer and use it in GitHub Desktop.
PowerShell binary rotate right/left on individual bytes
function Rotate-Byte {
<#
.SYNOPSIS
Performs left/right binary rotation on individual bytes.
Author: @harmj0y
.DESCRIPTION
Implements the logic to perform per-byte binary rotates right and left.
Use a positive offset value to rotate right, negative to rotate left.
.PARAMETER Value
The individual byte value, or array of byte values, to bit rotate.
Passable on the pipeline.
.PARAMETER Offset
The number of bits to rotate, [-8..8]. Positive values rotate right, negative
rotate left.
.OUTPUTS
[Byte[]]. Returns a stream of bit-rotated bytes.
.EXAMPLE
PS > 131 | Rotate-Byte
56
Rotate 131 right by 4 bits.
.EXAMPLE
PS > Rotate-Byte 131 -3
28
Rotate 131 left by 3 bits.
.EXAMPLE
PS > [Byte[]]$Bytes = @(131, 130, 129)
PS > $Bytes | Rotate-Byte
56
40
24
Rotates all bytes right by 4 bits.
.EXAMPLE
PS > @(131, 130, 129) | Rotate-Byte -Offset -2
14
10
6
Rotates all bytes left by 2 bits.
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $True)]
[Byte[]]
$Value,
[Parameter(Position = 1)]
[Int]
[ValidateRange(-8,8)]
$Offset = 4
)
PROCESS {
ForEach($Byte in $Value) {
if ($Offset -lt 0) {
1..(-$Offset) | ForEach-Object {
if($Byte -band 128) {
$Byte = 1 + ([Math]::Floor($Byte * [math]::Pow(2, 1)) -band 254)
}
else {
$Byte = [Math]::Floor($Byte * [math]::Pow(2, 1)) -band 254
}
}
}
else {
1..$Offset | ForEach-Object {
if($Byte -band 1) {
$Byte = 128 + [Math]::Floor($Byte * [math]::Pow(2, -1))
}
else {
$Byte = [Math]::Floor($Byte * [math]::Pow(2, -1))
}
}
}
$Byte
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment