Skip to content

Instantly share code, notes, and snippets.

@milot-mirdita
Last active May 5, 2025 22:04
Show Gist options
  • Save milot-mirdita/0ef9dafd457d91da859a52bf473f17d6 to your computer and use it in GitHub Desktop.
Save milot-mirdita/0ef9dafd457d91da859a52bf473f17d6 to your computer and use it in GitHub Desktop.
Replace xxd -i file on windows with powershell
#!/usr/bin/env pwsh
# Copyright (c) 2019 Milot Midita
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
$name = $args[0].ToLower() -replace '[^a-z0-9]','_'
$out = "unsigned char {0}[] = {{`n" -f $name
$i = 0
$bytes = Get-Content $args[0] -Encoding Byte -ReadCount 0
foreach ($b in $bytes) {
$out += if ($i -eq 0) { "`t" } elseif ($i -lt 12) { ", " } else { $i = 0; ",`n`t" }
$out += "0x{0:x2}" -f $b
$i++
}
$out += "`n}};`nunsigned int {0}_len = {1};" -f $name, $bytes.Count
Write-Output $out
@jqntn
Copy link

jqntn commented May 5, 2025

hi, here is a much faster version for handling large files:

$file_name = ($args[0] -replace '\W', '_').ToLower()
$file_bytes = [System.IO.File]::ReadAllBytes($args[0])
$hex_array = New-Object string[] $file_bytes.Length
for ($i = 0; $i -lt $file_bytes.Length; $i++) {
    $hex_array[$i] = '0x{0:x2}' -f $file_bytes[$i]
}
$hex_string = [string]::Join(', ', $hex_array)
"unsigned char $file_name[] = { $hex_string };"
"unsigned int ${file_name}_len = $($file_bytes.Length);"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment