Bash script that prints out contents of a binary file, one word at a time, without xxd

1.2k views Asked by At

I'd like to create a BASH script that reads a binary file, word (32-bits) by word and pass that word to an application called devmem.

Right now, I have:

...
for (( i=0; i<${num_words}; i++ ))
do
    val=$(dd if=${file_name} skip=${i} count=1 bs=4 2>/dev/null)
    echo -e "${val}" # Weird output...
    devmem ${some_address} 32 ${val}
done
...

${val} has some weird (ASCII?) format character representations that looks like a diamond with a question mark.

If I replace the "val=" line with:

val=$(dd ... | xxd -r -p)

I get my desired output.

What is the easiest way of replicating the functionality of xxd using BASH?

Note: I'm working on an embedded Linux project where the requirements don't allow me to install xxd.

This script is performance driven, please correct me if I'm wrong in my approach, but for this reason I chose (dd -> binary word -> devmem) instead of (hexdump -> file, parse file -> devmem). - Regardless of the optimal route for my end goal, this exercise has been giving me some trouble and I'd very much appreciate someone helping me figure out how to do this.

Thanks!

1

There are 1 answers

0
csikos.balint On BEST ANSWER

As I see you shouldn't use '|' or echo, because they are both ASCII tools. Instead I think '>' could work for you.
I think devmem is a bash function or alias, so I would try something like this:

for (( i=0; i<${num_words}; i++ ))
do
    dd if=${file_name} skip=${i} count=1 bs=4 2>/dev/null 1> binary_file
#    echo -e "${val}" # Weird output...
    devmem ${some_address} 32 $(cat binary_file)
done

"As cat simply catenates streams of bytes, it can be also used to concatenate binary files, where it will just concatenate sequence of bytes." wiki

Or you can alter devmem to accept file as input...I hope this will help!