【问题标题】:Convert ASCII code to hexadecimal in a Unix shell script在 Unix shell 脚本中将 ASCII 代码转换为十六进制
【发布时间】:2011-04-04 21:16:49
【问题描述】:

我想在 Unix shell 中将 ASCII 码(如 -_. 等)转换为 十六进制 表示(不带bc 命令)。例如,- => %2d

我该怎么做?

【问题讨论】:

  • 可以使用sed/awk/perl等吗?
  • 请只使用 sed 或 bash/sh shell ;)

标签: unix shell ascii hex


【解决方案1】:

这适用于 Bash、Dash (sh)、ksh、zsh 和 ash,并且仅使用内置函数:

编辑:

这是一个以十六进制输出的 ord 版本,以及接受十六进制输入的 chr:

ordhex ()
{
    printf '%x' "'$1"
}

chrhex ()
{
    printf \\x"$1"
}

原始十进制版本:

ord ()
{
    echo -n $(( ( 256 + $(printf '%d' "'$1"))%256 ))
}

示例(添加了换行符):

$ ord ' '
32
$ ord _
95
$ ord A
65
$ ord '*'
42
$ ord \~
126

这里是对应的chr

chr ()
{
    printf \\$(($1/64*100+$1%64/8*10+$1%8))
}

例子:

$ chr 125
}
$ chr 42
*
$ chr 0 | xxd
0000000: 00                                       .
$ chr 255 | xxd
0000000: ff                                       .

【讨论】:

  • thx 但是 ord 函数给了我十进制值,我想要 ascii 码的十六进制值,谢谢你的帮助
【解决方案2】:
perl -e 'print ord("_"), "\n"'

【讨论】:

  • 非常感谢,我将在 unpack 中使用这个表达式: perl -e 'print unpack("H*","-"), "\n"'
【解决方案3】:

python -c '导入系统; print "{0:02x}".format(ord(sys.argv[1]))' '_'

python -c 'print "{0:02x}".format(ord("_"))'

我同意这不是最好的单行,但在看到基于 Perl 的答案后我无法抗拒。

【讨论】:

    【解决方案4】:

    以下在我使用的 ksh 版本中有效:

    chr ()
    {
        printf \\x$1
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      相关资源
      最近更新 更多