PowerShell Convert Byte Array to Hex String

As a PowerShell expert, I’ve encountered many scenarios involving converting byte arrays to hexadecimal strings. In this complete tutorial, I’ll walk you through multiple methods to convert byte arrays to hex strings in PowerShell with practical examples.

Let me first explain about byte arrays and hexadecimal representations. A byte array is a collection of bytes (values from 0 to 255), while a hexadecimal string represents these bytes as two-character hex values (00 to FF). This conversion is crucial when you need human-readable representations of binary data.

Method 1: Using BitConverter Class (My Recommended Approach)

In my experience, the System.BitConverter class provides one of the most straightforward methods for converting byte arrays to hex strings in PowerShell.

Here’s how I typically implement this:

# Create a sample byte array
$byteArray = @(72, 101, 108, 108, 111)

# Convert to hex string using BitConverter
$hexString = [System.BitConverter]::ToString($byteArray)

Write-Host "Hex String: $hexString"
# Output: 48-65-6C-6C-6F

You can see the exact output in the screenshot below:

PowerShell Convert Byte Array to Hex String

The output includes hyphens between each byte. If you need a continuous hex string without separators, I recommend using the -Replace operator:

$hexString = [System.BitConverter]::ToString($byteArray) -replace '-',''

Write-Host "Hex String (no hyphens): $hexString"
# Output: 48656C6C6F

Check out Convert Bytes to GB in PowerShell

Method 2: Using Format Operator with ForEach-Object

When I need more control over the formatting, I use PowerShell’s -f format operator combined with ForEach-Object.

Here is an example.

# Create a byte array
$byteArray = @(255, 128, 64, 32, 16)

# Convert each byte to 2-digit hex format
$hexString = ($byteArray | ForEach-Object { '{0:X2}' -f $_ }) -join ''

Write-Host "Hex String: $hexString"
# Output: FF80402010

This method gives you precise control over formatting:

  • {0:X2} formats the value as uppercase hexadecimal with 2 digits
  • {0:x2} would give you lowercase hexadecimal
  • The -join '' combines all hex values into a single string

Here is the exact output in the screenshot below:

Convert Byte Array to Hex String in PowerShell

Read Convert Bytes to Base64 String in PowerShell

Method 3: Using Format-Hex Cmdlet for Analysis

PowerShell’s built-in Format-Hex cmdlet is excellent when you need to analyze byte data with additional context. Here is a complete script and example.

# Create a byte array
$byteArray = @(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)

# Display formatted hex output
$byteArray | Format-Hex

# Output includes offset, hex values, and ASCII representation

While Format-Hex doesn’t directly produce a simple hex string, it’s invaluable for debugging and analysis purposes.

Check out Convert Base64 String to Byte Array in PowerShell

Method 4: Custom Function for Large Byte Arrays

Over the years, I’ve developed a custom function that handles large byte arrays efficiently:

function Convert-ByteArrayToHex {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [byte[]]$ByteArray,

        [Parameter(Mandatory=$false)]
        [string]$Separator = '',

        [Parameter(Mandatory=$false)]
        [switch]$Uppercase
    )

    process {
        $formatString = if ($Uppercase) { '{0:X2}' } else { '{0:x2}' }

        $hexValues = $ByteArray | ForEach-Object {
            $formatString -f $_
        }

        return $hexValues -join $Separator
    }
}

# Usage example
$byteArray = @(10, 20, 30, 40, 50)
$hexString = Convert-ByteArrayToHex -ByteArray $byteArray -Uppercase

Write-Host "Hex String: $hexString"
# Output: 0A141E2832

Check out Get String Length in Bytes in PowerShell

Convert Byte Array to Hex String in PowerShell Examples

Now, let me show you some examples of converting a byte array to a hex string in PowerShell.

Example 1: Converting Hash Values

I frequently work with cryptographic hashes that return byte arrays. Here’s how I convert them:

# Calculate SHA256 hash
$inputString = "PowerShell"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($inputString)
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$hashBytes = $sha256.ComputeHash($bytes)

# Convert to hex string
$hashHex = [System.BitConverter]::ToString($hashBytes) -replace '-',''

Write-Host "SHA256 Hash: $hashHex"

Example 2: Working with Network MAC Addresses

When dealing with network adapters, MAC addresses are often stored as byte arrays:

# Simulating a MAC address as byte array
$macBytes = @(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E)

# Convert to standard MAC format
$macAddress = ($macBytes | ForEach-Object { '{0:X2}' -f $_ }) -join ':'

Write-Host "MAC Address: $macAddress"
# Output: 00:1A:2B:3C:4D:5E

Example 3: Reading Binary Files

Here is another example: here’s how I handle binary file conversions:

# Read binary file content
$filePath = "C:\temp\sample.bin"
$fileBytes = [System.IO.File]::ReadAllBytes($filePath)

# Convert first 16 bytes to hex
$hexPreview = ($fileBytes[0..15] | ForEach-Object { '{0:X2}' -f $_ }) -join ' '

Write-Host "File Header (Hex): $hexPreview"

Check out Convert Byte Array To String In PowerShell

Performance Considerations

Based on my testing with various methods, here are my performance observations:

For small arrays (< 1KB):

  • BitConverter method: Fastest and most readable
  • Format operator method: Slightly slower but more flexible

For large arrays (> 1MB):

  • Use StringBuilder for optimal performance:
$byteArray = New-Object byte[] 1000000
$sb = New-Object System.Text.StringBuilder

foreach ($byte in $byteArray) {
    [void]$sb.AppendFormat("{0:X2}", $byte)
}

$hexString = $sb.ToString()

Convert Hex String Back to Byte Array in PowerShell

I always recommend understanding the reverse operation as well. Here is how to convert a Hex string back to a byte array in PowerShell.

function Convert-HexToByteArray {
    param([string]$HexString)

    # Remove any spaces or hyphens
    $HexString = $HexString -replace '[-\s]',''

    # Convert to byte array
    $byteArray = New-Object byte[] ($HexString.Length / 2)

    for ($i = 0; $i -lt $HexString.Length; $i += 2) {
        $byteArray[$i/2] = [Convert]::ToByte($HexString.Substring($i, 2), 16)
    }

    return $byteArray
}

# Example usage
$hexString = "48656C6C6F"
$byteArray = Convert-HexToByteArray -HexString $hexString
$originalString = [System.Text.Encoding]::UTF8.GetString($byteArray)

Write-Host "Original String: $originalString"
# Output: Hello

Read Convert String to Byte Array in PowerShell

Best Practices I Follow

After years of working with PowerShell, here are my recommended best practices:

  1. Choose the right method: Use BitConverter for simplicity, format operators for customization
  2. Handle large data efficiently: Implement StringBuilder for arrays larger than 1MB
  3. Validate input: Always check if your byte array is null or empty
  4. Consider memory usage: Process large files in chunks rather than loading everything into memory
  5. Document your code: Hex conversions can be confusing; add clear comments

Troubleshooting Common Issues

Here are two common issues I faced recently, so I thought of sharing with you.

Issue 1: Out of Memory Exceptions

Here is how to fix incase you got the out of memory exceptions.

# Instead of loading entire file
# $bytes = [System.IO.File]::ReadAllBytes($largefile)

# Process in chunks
$stream = [System.IO.File]::OpenRead($largefile)
$buffer = New-Object byte[] 4096
while (($read = $stream.Read($buffer, 0, 4096)) -gt 0) {
    $hexChunk = [System.BitConverter]::ToString($buffer, 0, $read)
    # Process hex chunk
}
$stream.Close()

Issue 2: Incorrect Padding

# Always ensure 2-digit format
$correctHex = '{0:X2}' -f $byte  # Good: "0A"
$incorrectHex = '{0:X}' -f $byte # Bad: "A"

Conclusion

In this tutorial, I explained different methods to convert arrays to hexadecimal strings in PowerShell.

My go-to recommendation is the BitConverter class for most scenarios due to its simplicity and performance. But you can try all the methods and let me know which one you find interesting.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.