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

标签 c character-encoding ascii m4

这应该是可能的,但由于我是 m4 的新手,我不确定如何去做,或者如何编写一个算法来做到这一点(在 m4 中)。

编辑:

刚刚解决了它,无论如何供将来引用,我有一系列字符,需要将它们转换为等效的 ASCII 代码点,例如

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

最佳答案

为了让其他对纯 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

关于c - 使用 m4 将字符串转换为 ASCII 代码点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907684/

相关文章:

c - 如何获得C函数的实际输出?

循环浏览一些数字

c++ - 处理从十六进制到十六进制的转换

java - 将非 ASCII 符号降级为最接近的 7 位 ASCII 等价物(最好是 Java)

c - Unix 中的 'whiteout' (S_IFWHT) 是什么?

python - 使用 ctypes 时释放内存

html - "&#160;"是 "&nbsp;"的替代品吗?

java - 如何防止将类似字符写入字符串?

delphi - 如何让 Delphi 2006 TStringList.LoadFromFile 加载 UTF-16 文件

vba - 如何在 MS Word VBA 中处理多字节符号