$theTitle=wp_title(" - ", false); if($theTitle != "") { ?>
About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like
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:
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 49 50 51 52 53 54 55 56 57 | 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)) |
One Response for "Convert Bin to Hex and Hex to Bin in PowerShell"
[…] And here is a usage example (the BinToHex and HexToBin functions are from my previous blog). […]
Leave a reply