问题
This should be possible, but as I am a novice with m4, I'm not sure how to go about it, or how to write an algorithm to do so (in m4).
edit:
Just solved it, anyway for future reference, I have a series of characters, they need to be translated to their equivalent ASCII code points, e.g.
ascii(-{COLON}-, -{:}-) => #define TKN_COLON 58
回答1:
For the benefit of others interested in a pure m4 implementation I've managed to create the following conversion macro. It has to meddle with the quoting characters to support normal m4 quote chars. It could be simplified a bit if that isn't important.
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
Usage:
asciiord(`hello') --> 104, 101, 108, 108, 111
回答2:
I accomplished this with the following code section
divert(-1)
changequote(-{,}-)
changecom(/*,*/)
define(-{ascii}-,-{#define TKN_-{}-$1 esyscmd(-{python -c "import sys; sys.stdout.write('%d'%ord('$2'))"}-)}-)
divert(0)dnl
I would greatly appreciate if anyone knows of a better way to do this (e.g. native m4, or more portable shell command).
来源:https://stackoverflow.com/questions/12907684/using-m4-to-convert-a-string-to-ascii-codepoints