Monday, October 10, 2022

[SOLVED] How do you convert characters to ASCII without use of the printf in bash

Issue

ascii() {printf '%d' "'$1"}

I am currently using this function to convert characters to ASCII, however I just want to store the result of the function as a variable without printing the ascii. How would I go about this? (please bear in mind I have only been using bash for a few hours total, so sorry if this is a dumb question.)


Solution

In bash, after

printf -v numval "%d" "'$1"

the variable numval (you can use any other valid variable name) will hold the numerical value of the first character of the string contained in the positional parameter $1.

Alternatively, you can use the command substitution:

numval=$(printf "%d" "'$1")

Note that these still use printf but won't print anything to stdout.

As stated in the comment by @Charles Duffy, the printf -v version is more efficient, but less portable (standard POSIX shell does not support the -v option).



Answered By - M. Nejat Aydin
Answer Checked By - Mary Flores (WPSolving Volunteer)