1

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.

3
  • 2
    The reason it's printing 0 is because that's the value it's reading. You are reading each character from the file, so the filechar value has the value of 0. The printf binary doesn't interpret the characters you pass to it as numbers. Can you not use od -tx $INPUTFILE? That should be POSIX-friendly. Commented Nov 18, 2016 at 21:08
  • @eddiem Maybe. Image a system that is so secure that it's impossible to use. This is why I am trying to do everything in bash, as that works. It's just a pipe nightmare. "od" is a good choice as it's been around forever. I didn't know about od until you mentioned it. I'll ask the admins if I can be sure everyone can run that. Commented Nov 18, 2016 at 21:20
  • You will have trouble with some character values: character 0 (ASCII NULL) cannot be represented in a shell variable or passed as an argument, and characters above 127 (hex 7f) may be problematic depending on your locale. Commented Nov 19, 2016 at 5:13

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.