RickyBobby
RickyBobby

Reputation: 65

Simple code to convert packed binary data to hex?

I have the following (working) code to convert packed binary data to hex. But I'd guess there is a better, simpler way than this. Or is there? I'm pretty much a beginner.

This code takes a byte array where each byte is comprised of two 4-bit hex digits (0-f), like 37 (00110111). The algorithm separates the "3" and "7" into 8-bit bytes expressed internally as a string. Thanks.

    #!/bin/bash
    aesKeyIv=""
    while read c; do
       c1=$((c >> 4))
       c2=$((c & 15))
       if ((c1 == 10)); then
          c1="a"
       elif ((c1 == 11)); then
          c1="b"
       elif ((c1 == 12)); then
          c1="c"
       elif ((c1 == 13)); then
          c1="d"
       elif ((c1 == 14)); then
          c1="e"
       elif ((c1 == 15)); then
          c1="f"
       fi
       if ((c2 == 10)); then
          c2="a"
       elif ((c2 == 11)); then
          c2="b"
       elif ((c2 == 12)); then
          c2="c"
       elif ((c2 == 13)); then
          c2="d"
       elif ((c2 == 14)); then
          c2="e"
       elif ((c2 == 15)); then
          c2="f"
       fi
       aesKeyIv+=$(printf "%s%s" "$c1" "$c2")
    done <<<$(hexdump -v -e '/1 "%u\n"' AesKeyIv.bin)

Upvotes: 0

Views: 50

Answers (1)

nneonneo
nneonneo

Reputation: 179677

The simplest option would be to use xxd’s “plain” style:

xxd -p -c0 file.bin

-c0 here tells xxd to use an infinite width output (i.e. to not split the output into separate lines); that won’t work on old versions of xxd, for which you might need e.g. -c99999 instead (replace 99999 with the size of your file).

Alternatively, if all you have is hexdump, you can use

hexdump -v -e '/1 "%02x"' file.bin

Do note that hexdump’s output won’t end in a newline in this case.

Upvotes: 2

Related Questions