Skip to content
Advertisement

Outputting a decimal value as two little-endian hex bytes to a file

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement