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.
0is because that's the value it's reading. You are reading each character from the file, so thefilecharvalue has the value of 0. Theprintfbinary doesn't interpret the characters you pass to it as numbers. Can you not useod -tx $INPUTFILE? That should be POSIX-friendly.