使用m4将字符串转换为ASCII码点

时间:2012-10-16 04:48:26

标签: c character-encoding ascii m4

这应该是可能的,但由于我是m4的新手,我不知道如何去做,或者如何编写算法(m4)。

编辑:

刚解决它,无论如何将来参考,我有一系列字符,它们需要被翻译成等效的ASCII码点,例如。

ascii(-{COLON}-, -{:}-) => #define TKN_COLON 58

2 个答案:

答案 0 :(得分:2)

为了对纯m4实现感兴趣的其他人的利益,我设法创建了以下转换宏。它必须插入引号字符以支持正常的m4引用字符。如果这不重要,可以简化一下。

changequote(<!,!>) # Change quotes so we can handle "`" and "'"

# Change quotes every time this macro is called
define(<!asciiord!>,<!changequote(<!,!>)<!!>_asciiord(<!$1!>)<!!>changequote`'dnl
!>)

# Convert chars one at a time in the string argument
define(<!_asciiord!>,<!ifelse(<!$1!>,,, dnl
  <!_aconv(substr(<!$1!>,0,1))<!!>ifelse(len(<!$1!>),1,,<!,!>) $0(substr(<!$1!>,1))!>)!>)

# Map ASCII chars to their integer index by position
# Control chars are not supported.
# If the comment character is changed you must alter the map accordingly
define(<!_aconv!>,<!ifelse(<!$1!>,<! !>,32,<!$1!>,<!#!>,35,dnl
  <!index(<!                                 !" $%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !>,<!$1!>)!>)!>)

changequote # Restore normal quoting chars

用法:

asciiord(`hello') --> 104, 101, 108, 108, 111

答案 1 :(得分:1)

我使用以下代码部分

完成了这项工作
divert(-1)
changequote(-{,}-)
changecom(/*,*/)
define(-{ascii}-,-{#define TKN_-{}-$1 esyscmd(-{python -c "import sys; sys.stdout.write('%d'%ord('$2'))"}-)}-)
divert(0)dnl

如果有人知道更好的方法(例如本机m4或更多便携式shell命令),我将不胜感激。