PowerShell Hex Functions

I wrote some basic functions to convert a string to hexadecimal, to convert hexadecimal to a string. Also a function to dump a string to it’s component bytes, listing on each line, the character, it’s ASCII code in hexadecimal, and ASCII code in decimal. Example output:

PS C:\> StringToHex "This is an example!@#"
5468697320697320616E206578616D706C65214023
PS C:\> HexToString "4861726B212053686F77206D6520616E206578616D706C653F3F"
Hark! Show me an example??
PS C:\> HexDump "So how is this?"
S 0x53 83
o 0x6F 111
  0x20 32
h 0x68 104
o 0x6F 111
w 0x77 119
  0x20 32
i 0x69 105
s 0x73 115
  0x20 32
t 0x74 116
h 0x68 104
i 0x69 105
s 0x73 115
? 0x3F 63

The code. They are basic functions, not Advanced Functions, so nothing fancy.

function StringToHex($i) {
    $r = ""
    $i.ToCharArray() | foreach-object -process {
        $r += '{0:X}' -f [int][char]$_
        }
    return $r
    }

function HexToString($i) {
    $r = ""
    for ($n = 0; $n -lt $i.Length; $n += 2)
        {$r += [char][int]("0x" + $i.Substring($n,2))}
    return $r
    }

function HexDump($i) {
    $i.ToCharArray() | foreach-object -process {
        $num = [int][char]$_
        $hex = "0x" + ('{0:X}' -f $num)
        "$_ $hex $num"
        }
    }

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *