[英]How can I output #define value
I am new to this forum so please go easy on me :) 我是这个论坛的新手,所以请放轻松我:)
I have the following in my code 我的代码中有以下内容
#define SYS_SBS 0x02
Whenever I try to use this and try to output,I get 2 as the value, however I want to get SYS_SBS as the output for my program. 每当我尝试使用它并尝试输出时,我都会得到2作为值,但是我想让SYS_SBS作为程序的输出。 Is there a way, I can do this.
有办法,我可以做到这一点。
I have no control over the source code. 我无法控制源代码。 I just have to output SYS_SBS.
我只需要输出SYS_SBS。
Additional Details: I cannot change some the header files. 其他详细信息:我无法更改某些头文件。 However I can change the main function in .cpp file.
但是,我可以更改.cpp文件中的主要功能。 I want the SYS_SBS as the output.
我想要SYS_SBS作为输出。 I am working with satellites and for all the satellited detected by my receiver, I have to output what type of sattelite they are.
我正在处理卫星,对于接收器检测到的所有卫星,我必须输出它们是哪种类型的卫星。 In the code all of them are defined with this hexadecimal number.
在代码中,所有这些都使用此十六进制数字定义。 I just want to output SYS_SBS and not 2
我只想输出SYS_SBS而不是2
#include <stdio.h>
#define SYS_SBS 0x02
#define id(x) #x
int main(){
printf("%s %d\n", id(SYS_SBS), SYS_SBS);
return 0;
}
The C standard provides a stringification operator (add a # in front of the token) that allows you to outuput a specific token. C标准提供了一个字符串化运算符(在标记之前添加#),使您可以胜过特定的标记。
What's not possible is to convert backwards from a variable's value to this token name as this is lost during translations (as others have mentioned). 不可能将变量的值向后转换为该令牌名称,因为在转换过程中会丢失该令牌名称(如其他人所述)。 If you need that kind of conversion, think about a explicit "value2str" function that returns a string representation of a given value:
如果需要这种转换,请考虑一个显式的“ value2str”函数,该函数返回给定值的字符串表示形式:
const char *myType2str(int value)
{
switch (value)
{
case SYS_SBS:
return "SYS_SBS";
default:
return "UNKNOWN VALUE";
}
}
EDIT : According to some comments, stringification is part of the standard. 编辑 :根据一些评论,字符串化是标准的一部分。 Changed that.
改变了。 Thanks for the hint.
感谢您的提示。 Wasn't aware of that.
没意识到。
0x02
is the hexadecimal representation in the
source .
0x02
是
源中的十六进制表示形式。
Once you compiled it, it's just a number (2).
编译后,它只是一个数字(2)。
If you want to print it as hex, then, well... print it as hex (eg: use the formatting string
"0x%.2x"
).
如果要以十六进制形式打印,那么...将其打印为十六进制(例如:使用格式字符串
"0x%.2x"
)。
Well, you could simply: 好吧,您可以简单地:
printf("SYS_SBS");
But I assume you have a number as "input" (like 2), and want to output the string SYS_SBS
, well, that's not directly possible. 但是我假设您有一个数字作为“输入”(如2),并且想输出字符串
SYS_SBS
,这是不可能的。 The best you can do is create a lookup table, eg: 您可以做的最好的事情就是创建一个查询表,例如:
const char* sys_strings[] = { "SYS_EX", "SYS_TEM", "SYS_SBS" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.