Problems converting decimal to ASCII and back to decimal

Hi,
i have this function to get the ASCII of a decimal

function chr() {
  printf "\\$(printf '%03o' "$1")";
  return 0;
}

and this one to get the decimal back

function ord()
{
  printf '%d' "'$1";
  return 0;
}

but i can't get these to work for decimal 10 which is the NL line feed, new line char

ord "$(chr 10)"

gives me 0 (zero).

Any help, please?

Your code works for me:

[~] 0 $ type ord ; type chr
ord ist eine Funktion.
ord () 
{ 
    printf '%d' "'$1";
    return 0
}
chr ist eine Funktion.
chr () 
{ 
    printf "\\$(printf '%03o' "$1")";
    return 0
}
[~] 0 $  ord $(chr 97)
97[~] 0 $ 

EDIT:
Letters do not start at 0 or 1... but much later :wink:

Yes 97 works, but not 10.
The problem is that the $( ) (likewise the ` ` ) strips a trailing newline; this is mostly for convenience.

x="
"; echo ${#x}
1
x=$(echo "
"); echo ${#x}
0

--- Post updated at 15:54 ---

A stackoverflow article mentions a work-around. But the extra read options are likely not portable

IFS= read -r -n 1 -d '' x < <(chr 10)
echo ${#x}
1
ord "$x"
10

Hi
There is Dynamic Extensions in gnu awk

awk -lordchr 'BEGIN {print ord(chr(10))}'

Not sure if this is what you re after but fully POSIX compliant:-
Longhand OSX 10.14.3, default bash terminal calling dash.

Last login: Wed Apr 29 21:46:11 on ttys000
AMIGA:amiga~> dash
AMIGA:\u\w> ord()
> {
>     printf "%u\n" "'${1}"        
> }
AMIGA:\u\w> ord "
> "
10
AMIGA:\u\w> exit
AMIGA:amiga~> _
2 Likes

A workaround POSIX shell compliant.

#!/bin/sh

# #!/usr/local/bin/dash
# newline.sh

printf "\nA test.\n\n" > /tmp/nl

for subscript in 0 1 2 3 4 5 6 7 8 9
do
    nl=$( hexdump -n1 -s${subscript} -v -e '1/1 "%04o"' < /tmp/nl )
    printf "%u\n" "${nl}"
done

I'll leave you to create the function...
OSX 10.14.3, default bash terminal calling 'sh' or 'dash'...

Last login: Thu Apr 30 16:16:02 on ttys000
AMIGA:amiga~> cd Desktop/Code/Shell
AMIGA:amiga~/Desktop/Code/Shell> ./newline.sh
10
101
32
164
145
163
164
46
10
10
AMIGA:amiga~/Desktop/Code/Shell> _