Last active
January 4, 2019 08:28
-
-
Save quonic/09d573a216f68971e77cacc131461eb4 to your computer and use it in GitHub Desktop.
ConvertTo-Bits converts any string, number or an array of numbers to a bit array object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ConvertTo-Bits { | |
<# | |
.SYNOPSIS | |
This converts any string, number or an array of numbers to a bit array object | |
.DESCRIPTION | |
This converts any string, number or an array of numbers to a bit array object | |
.PARAMETER InputObject | |
Accepts any object, but String or Number is expected | |
.PARAMETER ToKeyValuePair | |
This changes the output to Key Value pairs | |
.PARAMETER LittleEndian | |
This returns the bit array in Little Endian format | |
.EXAMPLE | |
1..10 | ConvertTo-Bits | |
.EXAMPLE | |
1..10 | ConvertTo-Bits -ToKeyValuePair | |
.EXAMPLE | |
"A" | ConvertTo-Bits | |
.EXAMPLE | |
"AzXg3" | ConvertTo-Bits -ToKeyValuePair | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true, | |
Position = 0, | |
ValueFromPipeline = $true)] | |
$InputObject, | |
[switch] | |
$ToKeyValuePair, | |
[switch] | |
$LittleEndian | |
) | |
Process { | |
$isInt = $false | |
if ($InputObject.GetType().Name -like "String") { | |
[char[]]$data = $InputObject.ToCharArray() | |
} | |
elseif ($InputObject -eq [Int]) { | |
$data = $InputObject | |
$isInt = $true | |
} | |
else { | |
$data = $InputObject | |
} | |
$data | ForEach-Object { | |
if (-not $isInt) { | |
$a = [Convert]::ToInt64($_); | |
} | |
else { | |
$bits = [Convert]::ToByte([byte[]]$_, 10) | |
} | |
$bits = $( | |
$a -band 1 | |
while ($a -ne 0) { | |
# We shift the bits to the right by one. Removing the bit on the right. | |
$a = $a -shr 1 | |
$a -band 1 | |
} | |
) | |
if (-not $LittleEndian) { | |
<# | |
# Change the Endian to Little Endian be default | |
# We have to reverse the array to get Little Endian | |
# Little Endian = most significant bit on the right(largest value) | |
# 0x01 = 2 | |
# Where Bit Endian = most significant bit on the left | |
# 0x01 = 1 | |
#> | |
[Array]::Reverse($bits) | |
} | |
if ($ToKeyValuePair) { | |
@{ | |
$_ = $bits | |
} | |
} | |
else { | |
$bits | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment