C macro : turn a number into a string

谁说胖子不能爱 提交于 2019-12-05 07:49:38

You can concatenate strings in C source:

printf("%s\n", "forty" "two"); /* prints "fortytwo" */
/* NOTE:             ^^^ no punctuation */

To do that with your symbols is a lot of work, but maybe you can live with that.

#define SYMBOL_LEFT_ARROW 120
#define SYMBOL_LEFT_ARROW_STR "\x79"
#define SYMBOL_RIGHT_ARROW (SYMBOL_LEFT_ARROW + 1)
#define SYMBOL_RIGHT_ARROW_STR "\x83"
const char * const message = "Next" SYMBOL_RIGHT_ARROW_STR;

UPDATE

If you can make the value of the symbol match its position in the symbol table (120 match "\x78"), try these macros

#include <stdio.h>

#define ADD_ZERO_X(y) 0x ## y
#define SYMBOL_NUM(x) ADD_ZERO_X(x)

#define STRINGIZE(z) #z
#define ADD_SLASH_X(y) STRINGIZE(\x ## y)
#define SYMBOL_STR(x) ADD_SLASH_X(x)

#define SYMBOL_LEFT_ARROW 78 /* must write in hexadecimal without any prefix */
#define SYMBOL_RIGHT_ARROW 79
#define SYMBOL_UP_ARROW 7a

int main(void) {
  printf("%d\n", SYMBOL_NUM(SYMBOL_LEFT_ARROW));
  printf("%s\n", SYMBOL_STR(SYMBOL_LEFT_ARROW));
  printf("%d\n", SYMBOL_NUM(SYMBOL_RIGHT_ARROW));
  printf("%s\n", SYMBOL_STR(SYMBOL_RIGHT_ARROW));
  printf("%d\n", SYMBOL_NUM(SYMBOL_UP_ARROW));
  printf("%s\n", SYMBOL_STR(SYMBOL_UP_ARROW));
  return 0;
}

Edit (SO doesn't like my browser)

After macro expansion SYMBOL_NUM(32) is transformed to a integer literal (0x78); and SYMBOL_STR(78) is transformed to a string literal ("\x78").

You can use the literals as if you had typed them in.

const char *test = "Next" SYMBOL_STR(78) " one";
/* same as
   const char *test = "Next\x78 one";
*/

I came up with this little program:

#include <stdio.h>

#define TEST_CHR '\x77'
#define VAL(x) #x
#define STRINGIFY(x) VAL(x)
int main()
{
   int x = TEST_CHR;
   char *yyy = "%d " STRINGIFY(TEST_CHR) "\n";

   printf(yyy,x);

   return 0;

}

the indirection in the macro is necessary so that your character gets expanded before the "#" turns it into a string. notice that the '\x77' value turns into a valid int when you use it that way...

This is best I could come up with, not perfect, but can be put in ROM:

const char message[] = {'N','e','x','t',SYMBOL_RIGHT_ARROW,EOS};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!