For an upcoming Blog post I needed to convert a Byte Array to a Hex string in PowerShell and vice versa.

PowerShell doesn't come with HexToBin or BinToHex functions so here's my attempt at it:

text Download
function BinToHex {
	param(
    [Parameter(
        Position=0,
        Mandatory=$true,
        ValueFromPipeline=$true)
	]
	[Byte[]]$Bin)
	# assume pipeline input if we don't have an array (surely there must be a better way)
	if ($bin.Length -eq 1) {$bin = @($input)}
	$return = -join ($Bin |  foreach { "{0:X2}" -f $_ })
	Write-Output $return
}

function HexToBin {
	param(
    [Parameter(
        Position=0,
        Mandatory=$true,
        ValueFromPipeline=$true)
	]
	[string]$s)
	$return = @()

	for ($i = 0; $i -lt $s.Length ; $i += 2)
	{
		$return += [Byte]::Parse($s.Substring($i, 2), [System.Globalization.NumberStyles]::HexNumber)
	}

	Write-Output $return
}

cls

$enc = [System.Text.Encoding]::ASCII

# Our sample string
$StrIn = "Hello World!"

# Convert sample string to Byte Array
$Bytes = $enc.GetBytes($StrIn)

# Convert the Byte Array to a Hex String
$Hex = BinToHex $Bytes

# Display the Hex String
"Hex string for {0} is {1}" -f $StrIn, $Hex

# And let's convert it back...
$Bytes = HexToBin $Hex
$StrOut = $enc.GetString($Bytes2)

# Display the result
"The string for Hex {0} is {1}" -f $Hex, $StrOut

# Also accepts pipeline input!
$enc.GetString(($Bytes | BinToHex | HexToBin))