Convert Hex to ASCII in PowerShell

22,802

Solution 1

Well, we can do something terrible and treat the HEX as a string... And then convert it to int16, which then can be converted to a char.

$hexString = "68 65 6c 6c 6f 57 6f 72 6c 64 7c 31 2f 30 38 31 35 7c 41 42 43 2d 31 35 02 08"

We have the string, now we can use the spaces to split and get each value separately. These values can be converted to an int16, which is a ascii code representation for the character

$hexString.Split(" ") | forEach {[char]([convert]::toint16($_,16))}

The only problem is that it returns an array of single characters. Which we can iterate through and concatenate into a string

$hexString.Split(" ") | forEach {[char]([convert]::toint16($_,16))} | forEach {$result = $result + $_}
$result

Solution 2

Much like Phil P.'s approach, but using the -split and -join operators instead (also, integers not needed, ASCII chars will fit into a [byte]):

$hexString = "68 65 6c 6c 6f 57 6f 72 6c 64 7c 31 2f 30 38 31 35 7c 41 42 43 2d 31 35 02 08"
$asciiChars = $hexString -split ' ' |ForEach-Object {[char][byte]"0x$_"}
$asciiString = $asciiChars -join ''
$asciiString
Share:
22,802
Admin
Author by

Admin

Updated on October 22, 2020

Comments

  • Admin
    Admin over 3 years

    I have a series of hex values which looks like this:

    68 65 6c 6c 6f 57 6f 72 6c 64 7c 31 2f 30 38 31 35 7c 41 42 43 2d 31 35 02 08
    

    I now need to convert this hex value to ASCII so that the result looks like:

    helloWorld|1/0815|ABC-15
    

    I tried so many things but I never came to the final code. I tried to use the convert-function in every imaginable way without any success.

    At the moment I use this website to convert, but I need to do this in my PowerShell script.