janjin
janjin

Reputation: 43

Swap or replace bytes in a binary file from command line

There already is a beautiful trick in this thread to write bytes to binary file at desired address with dd ,is there any way to swap bytes(e.g swap 0x00 and 0xFF), or replace bytes with common tools (such as dd)?

Upvotes: 3

Views: 2886

Answers (2)

Nikolaii99
Nikolaii99

Reputation: 115

dd has this functionality built-in via conv=swab, which "swaps every pair of input bytes". It's incredibly useful if you need to convert file formats from "byte-swapped" to "big-endian" (or vice versa):

dd if=file1.v64 of=file2.z64 conv=swab

Upvotes: 0

tshiono
tshiono

Reputation: 22042

Would you please try the following:

xxd -p input_file | fold -w2 | perl -pe 's/00/ff/ || s/ff/00/' | xxd -r -p > output_file
  • xxd -p file dumps the binary data file in continuous hexdump style.
  • fold -w2 wraps the input lines by every two characters (= every bytes).
  • perl -pe 's/00/ff/ || s/ff/00/' swaps 00 and ff in the input string. The || logic works as if .. else .. condition. Otherwise the input 00 is once converted to ff and immediately converted back to 00 again.
  • xxd -r -p is the reversed version of xxd -p which converts the input hexadecimal strings into binaries.

Upvotes: 2

Related Questions