The xxd command in Linux: creating and reverting hex dumps

Introduction

The xxd command is a versatile tool present in almost all Linux distributions that allows creating hexadecimal dumps of files and, at the same time, reversing that process to obtain the original file. Its simple syntax and multiple options make it an indispensable ally for developers, system administrators, and anyone who needs to inspect or modify data at the binary level.

What is xxd?

Originally part of the vim package, xxd functions as a converter between binary and hexadecimal representation. It can display the contents of a file in hexadecimal format with offset addresses and ASCII representation, or read a hexadecimal dump and reconstruct the binary.

Creating a hex dump

To generate a basic dump it suffices to redirect the output of xxd to a file:

  • xxd file > file.hex
  • xxd -p file > file.hex (flat output, only hexadecimal without addresses)
  • xxd -c 16 file > file.hex (sets the number of bytes per line, default 16)

Useful options when creating dumps

  • -l length: limits the output to the specified number of bytes.
  • -s offset: starts the dump from a given offset (in decimal, octal with 0o or hexadecimal with 0x).
  • -u: uses uppercase letters for the A‑F digits, which can improve readability in certain contexts.

Reverting a hex dump

The inverse process is performed with the -r option (revert). Depending on the dump format, variants are used:

  • xxd -r file.hex > file (revert a dump with addresses and ASCII)
  • xxd -r -p file.hex > file (revert a flat dump, only hexadecimal)

Practical examples

Below are some scenarios where xxd is particularly useful:

  1. Inspect the ELF header of an executable: xxd -l 64 /bin/ls shows the first 64 bytes, enough to see the magic number and file type.
  2. Modify a specific byte: create a dump, edit the hexadecimal value with a text editor, and repack it with xxd -r.
  3. Compare two binaries without executing them: generate flat dumps and use diff to detect byte-level differences.

Tips and best practices

  • Always work on a backup copy of the original file before applying changes via dumps.
  • Use xxd -p when you need a pure hexadecimal stream to pipe to other tools like grep or sed.
  • Combine xxd with od or hexdump according to whether you prefer offset representation or flat format.

Conclusion

The xxd command is a lightweight but powerful tool that simplifies the creation and reversal of hexadecimal dumps in Linux. Mastering its basic and advanced options will allow you to inspect, debug, and modify binary data with precision, saving time and avoiding errors in low-level tasks.

This post is also available in ESPAÑOL.

Leave a Reply

Your email address will not be published. Required fields are marked *

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .