如何在 C 中打开 4 个字符的字符串?
我需要根据 4 个字符的字符串进行切换。我将字符串放入联合中,这样我至少可以将其称为 32 位整数。
union
{
int32u integer;
char string[4];
}software_version;
但现在我不知道在案例陈述中该写什么。我需要某种宏来将 4 个字符的字符串文字转换为整数。 EG
#define STRING_TO_INTEGER(s) ?? What goes here ??
#define VERSION_2_3_7 STRING_TO_INTEGER("0237")
#define VERSION_2_4_1 STRING_TO_INTEGER("0241")
switch (array[i].software_version.integer)
{
case VERSION_2_3_7:
break;
case VERSION_2_4_1:
break;
}
有没有办法制作 STRING_TO_INTEGER() 宏。或者有更好的方法来处理切换吗?
I need to switch based on a 4-character string. I put the string in a union so I can at least refer to it as a 32-bit integer.
union
{
int32u integer;
char string[4];
}software_version;
But now I don't know what to write in the case statements. I need some kind of macro to convert a 4-character string literal into the integer. E.G.
#define STRING_TO_INTEGER(s) ?? What goes here ??
#define VERSION_2_3_7 STRING_TO_INTEGER("0237")
#define VERSION_2_4_1 STRING_TO_INTEGER("0241")
switch (array[i].software_version.integer)
{
case VERSION_2_3_7:
break;
case VERSION_2_4_1:
break;
}
Is there a way to make the STRING_TO_INTEGER() macro. Or is there a better way to handle the switch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可移植示例代码:
该代码仅假设存在整数类型
uint8_t
和uint32_t
,并且与char
类型的宽度和符号无关作为字节序。只要字符编码仅使用uint8_t
范围内的值,就不会发生冲突。Portable example code:
The code only assumes the existence of the integer types
uint8_t
anduint32_t
and is agnostic to width and signedness of typechar
as well as endianness. It is free of collisions as long as the character encoding only uses values in range ofuint8_t
.您可以像这样打开四字符代码,
请注意区别:
"XXXX"
是字符串,'XXXX'
是字符/整数文字。但是,我建议您使用单独的版本号,例如:
You switch on four-character-codes like this
Note the difference:
"XXXX"
is a string,'XXXX'
is a character/integer literal.However, I would propose you use seperate version numbers instead, e.g.:
更新:
Updated:
编辑:
EDIT: