且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C宏:将数字转换为字符串

更新时间:2023-02-03 07:54:08

您可以在C源代码中连接字符串:

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;



更新



如果您可以使符号的值与其在符号表中的位置匹配(120个匹配 \x78),请尝试以下宏

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;
}






编辑(所以不喜欢我的浏览器)

宏扩展后 SYMBOL_NUM(32)转换为整数文字( 0x78 );和 SYMBOL_STR(78)转换为字符串文字( \x78 )。

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";
*/