0

The following Javascript example reads and logs the first 100 bytes of a file selected by a user (via the file input):

var blob = file.slice(0, 100);            

var fileReader = new FileReader();
fileReader.onload = function(event) {
    var arrayBuffer = event.target.result;
    var bytes = new Uint8Array(arrayBuffer);
    console.log('bytes', bytes);
};

fileReader.readAsArrayBuffer(blob);

What is the equivalent to achieve the same via a Linux utility like hexdump or od?

UPDATE: I am looking for hexdump -d but producing single byte decimals, instead of 2 byte decimals.

jww
  • 97,681
  • 90
  • 411
  • 885
jeffreyveon
  • 13,400
  • 18
  • 79
  • 129
  • `hexdump` has a `-n` option to show only the requested number of bytes. – Pointy Apr 01 '19 at 15:59
  • `hexdump -d` is the closest to what I am looking for. But I want single byte decimals, instead of the 2-bytes decimals that `hexdump -d` displays. – jeffreyveon Apr 01 '19 at 16:11
  • Possible duplicate of [How to create a hex dump of file containing only the hex characters without spaces in bash?](https://stackoverflow.com/q/2614764/608639), [How to view files in binary from bash?](https://stackoverflow.com/q/1765311/608639), [Commandline hexdump with ASCII output?](https://stackoverflow.com/q/23416762/608639), etc. – jww Apr 01 '19 at 16:19
  • `hexdump -n 100 -v -e '/1 "%02X\n"'` — `hexdump` formatting syntax is bizarre, to say the least *edit* oh wait, decimals; hold on - `hexdump -n 100 -v -e '/1 "%02d\n"'` – Pointy Apr 01 '19 at 16:21
  • @Pointy Bingo. Thank you. If you can add a answer, I will accept. None of the potentially duplicate answers pointed above actually answer my question directly. – jeffreyveon Apr 01 '19 at 16:39

1 Answers1

2

You can do this with hexdump. The formatting syntax for hexdump is, to say the least, somewhat weird, and the standard man page doesn't help much.

The tl;dr version is:

hexdump -n 100 -v -e '/1 "%03d\n"' your-file

You could use just %d if you don't care about leading zeros.

Now what that means:

  • -n 100 says to look only at the first 100 bytes of the input
  • -v says to show every byte. Ordinarily, repeats are collapsed to an * in the output.
  • -e '/1 "%03d\n"' is the format string (more below)

The format string consists of "stanzas" that start with a n/m indicator of how to count and group bytes. /1 means that the input should be processed in groups of 1 byte each. After the count/grouping indicator comes a format string, basically in the style of printf() formats.

Here is a fairly good explanation of hexdump courtesy of the Suse folks.

Pointy
  • 405,095
  • 59
  • 585
  • 614