b degnan
b degnan

Reputation: 692

Bash, converting byte to ascii hex without hexdump or xxd

I want to convert a binary file to an ASCII representation of hex. This is actually due to a weird portability issue in sharing my academic work. The motivation is that it is easier to have a file represented in hex as large values printed in ASCII. I have the unique situation where I have BASH, but might not have xxd or hexdump. I was trying to make a bash script that takes a file, reads a byte, and then outputs a value as ASCII hex. I thought printf would be the way to go, but if the file has binary 0x30, it prints out ASCII "0".

#!/bin/sh
INPUTFILE=$1
while IFS= read -r -n1 filechar
do
  printf  "%02X" "$filechar"
done < "$INPUTFILE"
printf "\n"

I am unclear why "%02X" is not returning "30" for the ascii value of "0". Again, the real crux of the problem is that I am trying to ONLY use Bash because I cannot guarantee that anyone has anything but Bash. To make matters worse, I'm trying for Bash 3.x. Any suggestions would be most welcome.

Upvotes: 1

Views: 1738

Answers (2)

b degnan
b degnan

Reputation: 692

I figured out a way, albeit terrible by loading the file into a string.

#!/bin/sh
FILESTRING=$(<$1)
for ((i=0;i<${#FILESTRING};i++));
do 
   printf %02X \'${FILESTRING:$i:1};
done

In this method, I need no external executable so I do not have to worry about anything outside of Bash. Thanks to everyone who commented.

Upvotes: 0

chepner
chepner

Reputation: 531165

If the character is preceded with an apostrophe, the ASCII value of the character is used.

printf  "%02X" "'$filechar"

I don't believe this will work for non-ASCII (> 127) characters, however.

Upvotes: 1

Related Questions