When working with binary files or low-level data manipulation, we often need to write raw hexadecimal values directly to a file without ASCII/Unicode conversion. This is particularly important for:
- Creating binary file headers
- Writing firmware images
- Generating test patterns
- Reverse engineering tasks
Here are several reliable methods to achieve this:
Using printf with xxd
printf '\xf6\x05\x00\x00\xac\x7e\x05\x00\x02\x00\x08\x00\x01\x00\x00\x00' > newfile
xxd newfile
Perl One-Liner
perl -e 'print pack("H*", "f6050000ac7e05000200080001000000")' > newfile
Python Approach
python -c 'open("newfile","wb").write(bytes.fromhex("f6050000ac7e05000200080001000000"))'
Always verify your file contents using hexdump or xxd:
hexdump -C newfile
00000000 f6 05 00 00 ac 7e 05 00 02 00 08 00 01 00 00 00 |.....~..........|
00000010
For more complex scenarios, you can combine these tools:
{
printf '\x7f\x45\x4c\x46' # ELF magic number
printf '\x02' # 64-bit
printf '\x01' # Little endian
printf '\x01' # ELF version
} > elf_header
Note that some methods may behave differently across operating systems. The Python approach tends to be most portable, while printf solutions might require adjustments on Windows systems.
When working with binary file formats, firmware images, or low-level protocols, we often need to create files containing specific hexadecimal values that don't correspond to printable ASCII characters. Traditional text editors and echo commands fail here because they convert input to ASCII representations.
Here are several reliable methods to achieve direct hex-to-binary conversion:
# Method 1: Using xxd (reverse mode)
echo "f6050000 ac7e0500 02000800 01000000" | xxd -r -p > output.bin
# Method 2: Using printf (built-in to most shells)
printf '\xf6\x05\x00\x00\xac\x7e\x05\x00\x02\x00\x08\x00\x01\x00\x00\x00' > output.bin
# Method 3: Using hexedit (interactive)
hexedit --new output.bin
# Then enter values in hexadecimal view
For complex binary patterns, we can combine tools:
# Generate sequence with Python then convert
python3 -c "import sys; sys.stdout.buffer.write(bytes.fromhex('f6050000ac7e05000200080001000000'))" > output.bin
# Using dc (desk calculator) for numeric conversions
dc -e "16i F6050000 P" | xxd -r -p > output.bin
Always verify your output:
hexdump -C output.bin
# Expected output:
# 00000000 f6 05 00 00 ac 7e 05 00 02 00 08 00 01 00 00 00 |.....~..........|
# 00000010
For large files (>1MB), consider these optimized approaches:
# Using dd with conv=notrunc for patching existing files
printf '\xf6\x05\x00\x00' | dd of=existing.bin bs=1 seek=0 count=4 conv=notrunc
# Using perl for complex binary operations
perl -e 'print pack("H*", "f6050000ac7e05000200080001000000")' > output.bin