Convert ascii to hex with 0x as leader

Hello,

I already have:

$StringToConvert = Read-Host ‘Enter string to convert to hex’

$HexValue = New-Object System.Text.StringBuilder

foreach ($Element in $StringToConvert.ToCharArray()) {
[void]$HexValue.Append(’{0:x}’ -f [System.Convert]::ToUInt32($Element))
$StringLength++
}

$HexValue = $HexValue.ToString()

$HexValue -split ‘(?<=\G[0-9a-f]{2})(?=.)’ -join ’ ’

But this gives something like 68 61 6c 6c 6f

I’m looking for something to make it in a 0x68, 0x61, 0x6c, 0x6c, 06f
Goal is to use this as part of a bigger hex value:
0x10, 0x02, “hex-value-from-above”, 0x10, 0x03

Then the purpose is to use this “total-hex” as data to be written via socket
But that part I have already.

Dre83,
Welcome to the forum. :wave:t4:

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

PowerShell has a cmdlet Format-Hex. So you don’t need to recreate it. :wink:

$InputString = Read-Host 'Enter string to convert to hex'

$HexArray = 
$InputString.ToCharArray() |
    ForEach-Object {
        '0x{0}' -f (($_ | Format-Hex).HexBytes)
    }
$HexArray -join ', '
1 Like