Thursday, December 20, 2012

Shell script: Convert decimal to ascii values

Q. I want to convert a given decimal number to ascii value, How can I do that using a shell script?

Below script will give you the ascii value corresponding number

#!/bin/bash

printf "Please enter a value between 32 to 127(Range of ascii values): "
read VAL1
printf "\\$(printf "%o" $VAL1)\n"

Let me explain this script. The script will take input from user in to VAL1 variable and pass it to printf command. printf "%o" $VAL1 will try to change the decimal value to octal. then this octal value is once again feed to the second printf as printf "\octvalue\n". printf command have one option what ever followed after \ will be treated as octal which helps use to convert to ascii values.   Want to print all the ascii values? Execute below script to do that   #!/bin/bash
for i in {32..127}
do
printf "\\$(printf "%o" $i)\n"
done

or just one single liner which will work in bash version 4 and above.    printf  "$(printf "\%o\n" {32..127})"   Please comment your thoughts on this.

0 comments:

Post a Comment