<分区>
Possible Duplicate:
Integer ASCII value to character in BASH using printf
我想将我的整数转换为 ASCII 字符
我们可以像这样在java中转换:
int i = 97; //97 is "a" in ASCII
char c = (char) i; //c is now "a"
但是,有什么办法可以执行此 shell 脚本吗?
<分区>
Possible Duplicate:
Integer ASCII value to character in BASH using printf
我想将我的整数转换为 ASCII 字符
我们可以像这样在java中转换:
int i = 97; //97 is "a" in ASCII
char c = (char) i; //c is now "a"
但是,有什么办法可以执行此 shell 脚本吗?
最佳答案
#!/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
编辑:
如您所见,ord()
有点棘手 -- 在整数前放置单引号。
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."
(摘自 http://mywiki.wooledge.org/BashFAQ/071 )。
参见 man printf(1p) .
关于bash - shell 脚本 - 有没有办法将数字转换为字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855610/