Skip to content

Instantly share code, notes, and snippets.

@dstebila dstebila/hex2bin.sh

Last active May 28, 2020
Embed
What would you like to do?
Shell script to convert hex file to binary, stripping out any comments
#!/bin/bash
# Read either the first argument or from stdin (http://stackoverflow.com/questions/6980090/bash-read-from-file-or-stdin)
cat "${1:-/dev/stdin}" | \
# Strip out comments starting with #
sed -E 's/#.*$//' | \
# Strip out comments starting with //
sed -E 's/\/\/.*$//' | \
# Strip out multi-line comments /* ... */
perl -0777 -pe 's{/\*.*?\*/}{}gs' | \
# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \
# Strip out all non hexadecimal characters
sed -E 's/[^0-9a-fA-F]*//g' | \
# Convert hex to binary using xxd's reverser in plain hexdump style
xxd -r -ps
@cxw42

This comment has been minimized.

Copy link

cxw42 commented May 28, 2020

Thank you for this script! In order to support files containing 0x.. entries, I added one transformation between lines 10 and 11 (after the first perl):

# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \
@dstebila

This comment has been minimized.

Copy link
Owner Author

dstebila commented May 28, 2020

Thank you for this script! In order to support files containing 0x.. entries, I added one transformation between lines 10 and 11 (after the first perl):

# Strip "0x" prefixes
perl -0777 -pe 's{\b0x(..)\b}{$1}gi' | \

Good suggestion, I've updated it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.