[NoBrainer] Convert byte array to hex string in PowerShell

This is a rather quick one and I am merely writing it down as I tend to forget … If you need a quick way to get a hex representation in string form (of a byte array or any string) you can use this fragment.

PS > $ab = [System.Text.Encoding]::UTF8.GetBytes('tralala');
PS > [System.BitConverter]::ToString($ab);
74-72-61-6C-61-6C-61

You certainly can combine this with some hash computation if you do not want a huge hex string:

PS > $sha1 = New-Object System.Security.Cryptography.SHA1Managed;
PS > $sha1.Initialize();
PS > $ab = $sha1.ComputeHash([System.Text.Encoding]::UTF8.GetBytes('tralala'));
PS > [System.BitConverter]::ToString($ab);
BB-31-FB-FF-8F-AC-91-C1-7E-E6-05-2D-98-08-4E-6E-63-18-48-59
PS > $sha1.Dispose();

Comments

  1. To convert bytes to a hex string:

    -join ($bytes | % {“{0:X2}” -f $_})

    • Ronald Rink says:

      Hi Joe, thanks for sharing. I just wanted to point out that the use of the piped `ForEach` loop is by far slower than the native `BitConverter`. For a length of 80 bytes I get these results on my system:

      “` powershell
      PS > $bytes = [System.Text.Encoding]::UTF8.GetBytes(‘*’ * 80);
      PS > Measure-Command { for($c = 0; $c -lt 1000; $c++) { -join ($bytes | % {“{0:X2}” -f $_}) } } | Select TotalMilliseconds

      TotalMilliseconds
      —————–
      3739.5275

      PS > Measure-Command { for($c = 0; $c -lt 1000; $c++) { [System.BitConverter]::ToString($bytes); } } | Select TotalMilliseconds

      TotalMilliseconds
      —————–
      19.6392
      “`

      It’s a difference of a factor of far more than 100.

      And for completeness here are also the results for `StringBuilder.AppendFormat` and `String.Concat`:

      “` powershell
      PS > # try with StringBuilder
      PS > Measure-Command { for($c = 0; $c -lt 1000; $c++) { $sb = New-Object System.Text.StringBuilder; foreach($b in $bytes) { $null = $sb.AppendFormat(‘{0:X2}’, $b); }; $sb.ToString(); } } | Select TotalMilliseconds

      TotalMilliseconds
      —————–
      444.4628

      PS > # try with string concatenation
      PS > Measure-Command { for($c = 0; $c -lt 1000; $c++) { $result = ”; foreach($b in $bytes) { $result = [string]::Concat($s, (‘{0:X2}’ -f $b)); $result; } } } | Select TotalMilliseconds

      TotalMilliseconds
      —————–
      622.0839
      “`

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: