13

Possible Duplicate:
Integer ASCII value to character in BASH using printf

I want to convert my integer number to ASCII character

We can convert in java like this:

int i = 97;          //97 is "a" in ASCII
char c = (char) i;   //c is now "a"

But,is there any way in to do this shell scripting?

Community
  • 1
  • 1
natrollus
  • 321
  • 1
  • 4
  • 11

2 Answers2

24
#!/bin/bash
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value

chr() {
  printf \\$(printf '%03o' $1)
}

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

ord A
echo
chr 65
echo

Edit:

As you see ord() is a little tricky -- putting a single quote in front of an integer.

The Single Unix Specification: "If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote."

(Taken from http://mywiki.wooledge.org/BashFAQ/071).

See man printf(1p).

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Rahul Gautam
  • 4,749
  • 2
  • 21
  • 30
8
declare -i i=97
c=$(printf \\$(printf '%03o' $i))
echo "char:" $c
P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    Can you explain the part `printf \\$(printf '%03o' $i)`? – Boyang Feb 10 '16 at 22:43
  • @CharlesW.`printf '%03o' $i` converts from decimal to octal (`97` -> `141`). Then passing it with "\\" which printf understands (i.e. `printf \\141`) and prints a char for the octal sequence. From *info printf*:`'printf' interprets '\OOO' in FORMAT as an octal number (if OOO is 1 to 3 octal digits) specifying a character to print, and '\xHH' as a hexadecimal number (if HH is 1 to 2 hex digits) specifying a character to print.` – P.P Feb 17 '16 at 10:22
  • I think the `03` zero padding is unnecessary? – wisbucky Dec 06 '19 at 21:41
  • 1
    For completeness: `printf "\x$(printf "%x" "$i")"` – glenn jackman Jan 20 '21 at 14:24