Roc*_*net 2 c string macros switch-statement
我需要根据4个字符的字符串进行切换.我把字符串放在一个联合中,所以我至少可以把它称为32位整数.
union
{
int32u integer;
char string[4];
}software_version;
Run Code Online (Sandbox Code Playgroud)
但现在我不知道在案例陈述中写什么.我需要某种宏来将4个字符的字符串文字转换为整数.例如
#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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法制作STRING_TO_INTEGER()宏.或者有更好的方法来处理交换机?
便携式示例代码:
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#define CHARS_TO_U32(c1, c2, c3, c4) (((uint32_t)(uint8_t)(c1) | \
(uint32_t)(uint8_t)(c2) << 8 | (uint32_t)(uint8_t)(c3) << 16 | \
(uint32_t)(uint8_t)(c4) << 24))
static inline uint32_t string_to_u32(const char *string)
{
assert(strlen(string) >= 4);
return CHARS_TO_U32(string[0], string[1], string[2], string[3]);
}
#define VERSION_2_3_7 CHARS_TO_U32('0', '2', '3', '7')
#define VERSION_2_4_1 CHARS_TO_U32('0', '2', '4', '1')
int main(int argc, char *argv[])
{
assert(argc == 2);
switch(string_to_u32(argv[1]))
{
case VERSION_2_3_7:
case VERSION_2_4_1:
puts("supported version");
return 0;
default:
puts("unsupported version");
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
代码仅假定存在整数类型uint8_t,uint32_t并且对于类型的宽度和签名char以及字节顺序是不可知的.只要字符编码仅使用范围中的值,它就没有冲突uint8_t.