Convert Hex to ASCII in PowerShell [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-11 03:09:19

问题


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.


回答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



回答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


来源:https://stackoverflow.com/questions/41762760/convert-hex-to-ascii-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!