Convert Hex to ASCII in PowerShell [duplicate]

2019-07-14 06:04发布

This question already has an answer here:

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.

2条回答
狗以群分
2楼-- · 2019-07-14 06:19

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
查看更多
beautiful°
3楼-- · 2019-07-14 06:41

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
查看更多
登录 后发表回答