11

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?

4

2 に答える 2

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).

于 2012-10-12T09:12:05.553 に答える
6
declare -i i=97
c=$(printf \\$(printf '%03o' $i))
echo "char:" $c
于 2012-10-12T09:11:18.083 に答える