Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Powershell functions to convert from byte array to hex or binary and vice versa.
$bits_in_a_byte = 8
$base2 = 2
$base16 = 16
Function ConvertTo-HexFromByteArray
{
param(
[parameter(Mandatory=$true)]
[Byte[]]
$bytes
)
$hex = [System.Text.StringBuilder]::new($bytes.Length * $base2)
ForEach($byte in $bytes)
{
# Default is two character format with just : X.
$hex.AppendFormat("{0:x2}", $byte) | Out-Null
}
$hex.ToString()
}
Function ConvertTo-ByteArrayFromHex
{
param(
[parameter(Mandatory=$true)]
[String]
$hex
)
$bytes = [byte[]]::new($hex.Length / $base2)
for($i=0; $i -lt $hex.Length; $i+=$base2)
{
$bytes[$i/$base2] = [Convert]::ToByte($hex.Substring($i, $base2), $base16)
}
$bytes
}
Function ConvertTo-BinFromByteArray
{
param(
[parameter(Mandatory=$true)]
[Byte[]]
$bytes
)
($bytes | %{ [Convert]::ToString($_,2).PadLeft($bits_in_a_byte,'0') }) -JOIN " "
}
Function ConvertTo-ByteArrayFromBin
{
param(
[parameter(Mandatory=$true)]
[String]
$bin
)
$binStr = $bin -Replace '\s', ''
$byteArrSize = $binStr.Length / $bits_in_a_byte
$bytes = [byte[]]::new($byteArrSize)
for($i=0; $i -lt $byteArrSize; $i++)
{
$bytes[$i] = [Convert]::ToByte($binStr.Substring($i*$bits_in_a_byte, $bits_in_a_byte), $base2);
}
$bytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment