-2

I have a need for a bash command that does the following:

Write a new file in which the two first bytes contain the raw hex bytes (not ASCII) of a value (start address in this case). I.e., 49152 should be written to the file as 00 c0.

I tried several combinations of printf, xxd, fold, tac/cat etc.

printf "%X\\n" 49152 | fold -w2|tac|tr -d "\n" 

This presents me with the ASCII representation of what I need, not the raw HEX bytes.

jww
  • 97,681
  • 90
  • 411
  • 885
  • 1
    This is about creating a binary file that starts with the start address of the code that follows. So $C000 would be the start address of the program that comes after the 2 first bytes. – Jacco de Wijs Sep 19 '19 at 17:18
  • hexdump would only work on files, this is supposed to be used in a command line – Jacco de Wijs Sep 19 '19 at 17:34
  • Did you try this: `{ dd if=/dev/zero bs=1 count=1 2>/dev/null; printf $'\xc0'; } >yourfile.bin` ? – Léa Gris Sep 19 '19 at 17:38
  • The thing is, the $c000 (49152) is a variable, not a fixed value. – Jacco de Wijs Sep 19 '19 at 17:42
  • Bash is really a poor choice for handling binary data. You could do arithmetics to transform an integer into your endian two bytes, and offload to `dd` for null bytes that bash can not produce. What the point? Use Python or even Perl or any other language that can deal with binary data. – Léa Gris Sep 19 '19 at 17:47
  • I guess i'd better start learning Python then... Isn't there a simple way to write the hex value of the printf statement above to a file, instead of its ASCII representation? (Convert ASCII to binary data) – Jacco de Wijs Sep 19 '19 at 17:52
  • [Write hexadecimal values to binary file with Bash](https://unix.stackexchange.com/q/377452), [How to write a binary file using Bash?](https://stackoverflow.com/q/5582778/608639), [How to write binary data in Bash](https://stackoverflow.com/q/43214001/608639), [How to write integer to binary file using Bash?](https://stackoverflow.com/q/9955020/608639), [How to create binary file using Bash?](https://stackoverflow.com/q/8521240/608639), etc. – jww Sep 19 '19 at 18:07
  • 1
    `printf`, `xxd`, `tac`, `fold` and `tr` are not `bash`, so if they are ok, presumably so are `Perl` and `Python` which would, IMHO, be better (less clumsy) choices. – Mark Setchell Sep 19 '19 at 19:07

1 Answers1

0
value=49152
printf "\x$(printf %x $(($value-$value/256*256)))\x$(printf %x $(($value/256)))" > file.txt

hexdump -C file.txt 

Output:

00000000  00 c0                                             |..|
00000002
Cyrus
  • 84,225
  • 14
  • 89
  • 153