Skip to content
Advertisement

Printf tab character as hex

In a restricted shell i have only access to execute printf (no awk, hexdump, xxd, …), so i used this script to print a file as hex:

a=$(<file.txt)
for ((i=0;i<${#a};i++));
do c=${a:$i:1}; 
    if [[ $c == ' ' ]]; then printf "%X" ' '; 
    elif [[ $c == $'r' ]]; then printf "%X" 'r'; 
    elif [[ $c == $'t' ]]; then printf "%X" 't'; 
    elif [[ $c == $'n' ]]; then printf "%X" 'n'; 
    else printf %02x '${a:$i:1};
    fi; 
done

issue: last line (printf %02x ‘${a:$i:1}) does not work for some character like s,r,n,t,… i handle space character with (printf “%X” ‘ ‘) but does not work for r,t and n

printf "%X" 't' ---> 74
printf "%X" "'t"  ---> 5C
printf "%X" '$"t"---> 5C

but it should return 09!

Advertisement

Answer

I’m getting 9 from

printf "%X" '$'t'

Quoting the expression should simplify the code, no ifs needed:

a=$(<file.txt)
for (( i=0 ; i < ${#a} ; i++ )) ; do
    c=${a:$i:1}
    printf %02x '"$c"
done
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement